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);
?>
get_file_contents()
earlier but it seems like my hosting has deactivated that function. allow_url_fopen = on
to php.ini didn't do the trick.Edit:
$obj->status
and $obj->results->location->lat
in
the else-statement, nothing showed up. So $obj
seems to be NULLIt seems it fails while verifying certificate, you could disable CA verification
To turn off certificate verification (for both peer and host verification) set the following options:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
Example
How to disable certificate verification
$address = "Ontario,CA";
$apiKey = "";
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . $address; //. "&key=" . $apiKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Disable SSL verification
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result);
print json_encode($result, JSON_PRETTY_PRINT);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With