获取 Google API 数据时 cURL 不起作用 [英] cURL not working while fetching Google API data
本文介绍了获取 Google API 数据时 cURL 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以,我正在尝试使用 cURL,但我从下面代码的 else 语句中收到消息失败".API 调用是用于获取坐标的 Google 地理编码.
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.
代码:
<?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()
,但似乎我的主机已停用该功能. - 将
allow_url_fopen = on
添加到 php.ini 没有解决问题. - 似乎我的托管允许 cURL,所以应该'不是问题.
- 我尝试手动转到 API 调用,但我得到了一个显示正确 JSON 数据的网页.
- SQL 查询似乎也运行良好.
- 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.
- 我尝试回显
$obj->status
和$obj->results->location->lat
else 语句,什么也没有出现.所以$obj
似乎是 NULL - I tried echoing
$obj->status
and$obj->results->location->lat
in the else-statement, nothing showed up. So$obj
seems to be NULL
推荐答案
好像验证证书失败,可以关闭CA验证
It 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);
示例
如何禁用证书验证
$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);
这篇关于获取 Google API 数据时 cURL 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文