Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function main() {
- // Set the parameters
- $input_file_name = 'input.csv';
- $output_file_name = 'output.csv';
- $error_file_name = 'error.csv';
- $delimiter = ',';
- // Check if we can read the input file
- if (!file_exists($input_file_name) || !is_readable($input_file_name)) {
- die('Cannot open input file!');
- }
- // Open all files
- $input_file = fopen($input_file_name, 'r');
- $output_file = fopen($output_file_name, 'w');
- $error_file = fopen($error_file_name, 'w');
- // Read the input file row-by-row until the end of file
- while (($row = fgetcsv($input_file, 1000, $delimiter)) !== FALSE) {
- $address = '';
- // Put together all columns except the first 2 and the last 3
- // This way - hopefully - we can handle any commas in the address field
- for ($i = 2; $i < count($row) - 3; $i++) {
- $address .= $row[$i] . ' ';
- }
- print 'Looking up "' . $address . '"... ';
- // Replace spaces with "+" sign so we can send it to the API
- $address = str_replace(" ", "+", $address);
- // Send request to the API
- $url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=$address";
- // Get the response in JSON format
- $response = file_get_contents($url);
- $json = json_decode($response,TRUE);
- // Check if we have any results
- if (count($json['results']) > 0) {
- print "ok\n";
- // Extract the results from the JSON array
- $lat = $json['results'][0]['geometry']['location']['lat'];
- $lng = $json['results'][0]['geometry']['location']['lng'];
- // Add the results to the row
- array_push($row, $lat, $lng);
- // Write row to the output
- fputcsv($output_file, $row);
- } else {
- print "not found :(\n";
- // No search results, put the row to errors
- fputcsv($error_file, $row);
- }
- // print 'Location: ' . $lat . '.' . $lng . "\n";
- // Sleep 0.2 seconds to avoid load limit per seconds
- usleep(200000);
- }
- // Close files, just to be sure
- fclose($output_file);
- fclose($error_file);
- }
- // Run our main function
- main();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement