Click here to Skip to main content
14,766,562 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:
 <?php 
    require_once('../db.php');
    $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, "https://maps.googleapis.com/maps/api/geocode/json?address=".$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";
        }
    }
    curl_close($ch);
?> 


What I have tried:

- 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.
Posted
Comments
Richard Deeming 16-Jun-16 8:34am
   
Rather than throwing away the error information, try echoing the properties of the $obj variable. That way, you'll be able to see the status, and possibly a detailed error message, which should tell you what the problem is.
AdamDedanga 16-Jun-16 9:04am
   
I tried echoing $obj->status and $obj->results->location->lat in the else statement, nothing showed up. So $obj seems to be NULL
Richard Deeming 16-Jun-16 9:06am
   
That doesn't sound right - does PHP really not throw an error if you try to access a member of a null object?

Try echoing the $json variable instead.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900