Advertisement
kraxor

Untitled

Nov 6th, 2013
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.08 KB | None | 0 0
  1. <?php
  2.  
  3. function main() {
  4.     // Set the parameters
  5.     $input_file_name = 'input.csv';
  6.     $output_file_name = 'output.csv';
  7.     $error_file_name = 'error.csv';
  8.     $delimiter = ',';
  9.    
  10.     // Check if we can read the input file
  11.     if (!file_exists($input_file_name) || !is_readable($input_file_name)) {
  12.     die('Cannot open input file!');
  13.     }
  14.  
  15.     // Open all files
  16.     $input_file = fopen($input_file_name, 'r');
  17.     $output_file = fopen($output_file_name, 'w');
  18.     $error_file = fopen($error_file_name, 'w');
  19.  
  20.     // Read the input file row-by-row until the end of file
  21.     while (($row = fgetcsv($input_file, 1000, $delimiter)) !== FALSE) {
  22.     $address = '';
  23.  
  24.     // Put together all columns except the first 2 and the last 3
  25.     // This way - hopefully - we can handle any commas in the address field
  26.     for ($i = 2; $i < count($row) - 3; $i++) {
  27.         $address .= $row[$i] . ' ';
  28.     }
  29.     print 'Looking up "' . $address . '"... ';
  30.  
  31.     // Replace spaces with "+" sign so we can send it to the API
  32.     $address = str_replace(" ", "+", $address);
  33.  
  34.     // Send request to the API
  35.     $url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=$address";
  36.  
  37.     // Get the response in JSON format
  38.     $response = file_get_contents($url);
  39.     $json = json_decode($response,TRUE);
  40.  
  41.     // Check if we have any results
  42.     if (count($json['results']) > 0) {
  43.         print "ok\n";
  44.        
  45.         // Extract the results from the JSON array
  46.         $lat = $json['results'][0]['geometry']['location']['lat'];
  47.         $lng = $json['results'][0]['geometry']['location']['lng'];
  48.  
  49.         // Add the results to the row
  50.         array_push($row, $lat, $lng);
  51.  
  52.         // Write row to the output
  53.         fputcsv($output_file, $row);
  54.     } else {
  55.         print "not found :(\n";
  56.        
  57.         // No search results, put the row to errors
  58.         fputcsv($error_file, $row);
  59.     }
  60.  
  61.     // print 'Location: ' . $lat . '.' . $lng . "\n";
  62.  
  63.     // Sleep 0.2 seconds to avoid load limit per seconds
  64.     usleep(200000);
  65.     }
  66.  
  67.     // Close files, just to be sure
  68.     fclose($output_file);
  69.     fclose($error_file);
  70. }
  71.  
  72. // Run our main function
  73. main();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement