cURL not working while fetching Google API data

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:

    $api_key = "somekey";
    $sqlQuery = mysql_query("SELECT `County` FROM `table`"); 
    $ch = curl_init();

    /* Fetch county */ 
    while($rows = mysql_fetch_array($sqlQuery))  { 
        $countyArr = $rows['County']; 

        /* Call google API and save coordinates for each county */ 
        curl_setopt ($ch, CURLOPT_URL, "".$countyArr.",+CA&key=".$api_key."");
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        $json= curl_exec($ch, true);
        $obj = json_decode($json);

        if ($obj->status == "OK") {
            $lat = $obj->results->location->lat;
            $lng = $obj->results->location->lng;
            echo $lat;
        } else {
            echo "fail";
  • 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.

Please don’t name a table “table”.

Does this work locally?
What is the full response of a failed request?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.