423,319 Members | 2,562 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 423,319 IT Pros & Developers. It's quick & easy.

cURL not working while fetching Google API data

P: 2
So, I'm trying to fetch API-data using cURL, but I get the message "fail" from the else-statement in the code below.
The API call is Google geocode for fetching coordinates.

The code:

Expand|Select|Wrap|Line Numbers
  1.  <?php 
  2.     require_once('../db.php');
  3.     $api_key = "somekey";
  4.     $sqlQuery = mysql_query("SELECT `County` FROM `table`"); 
  5.     $ch = curl_init();
  6.  
  7.  
  8.     /* Fetch county */ 
  9.     while($rows = mysql_fetch_array($sqlQuery))  { 
  10.         $countyArr = $rows['County']; 
  11.  
  12.         /* Call google API and save coordinates for each county */ 
  13.         curl_setopt ($ch, CURLOPT_URL, "https://maps.googleapis.com/maps/api/geocode/json?address=".$countyArr.",+CA&key=".$api_key."");
  14.         curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  15.         $json= curl_exec($ch, true);
  16.         $obj = json_decode($json);
  17.  
  18.         if ($obj->status == "OK") {
  19.             $lat = $obj->results->location->lat;
  20.             $lng = $obj->results->location->lng;
  21.             echo $lat;
  22.         } else {
  23.             echo "fail";
  24.         }
  25.     }
  26.     curl_close($ch);
  27. ?> 
  • I intended to use get_file_contents() earlier but it seems like my hosting has deactivated that function.
  • Adding allow_url_fopen = on to php.ini didn't do the trick.
  • It seems like my hosting allows cURL, so that shouldn't be the problem.
  • I've tried to manually go to the API-call and I get a webpage showing the correct JSON-data.
  • The SQL-query seems to be working fine too.
Jun 16 '16 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.