Php 获取Google API数据时cURL不工作
因此,我尝试使用获取API数据,但我从下面代码中的else语句中得到消息“fail”。 API调用用于获取坐标 代码:Php 获取Google API数据时cURL不工作,php,json,api,google-maps,curl,Php,Json,Api,Google Maps,Curl,因此,我尝试使用获取API数据,但我从下面代码中的else语句中得到消息“fail”。 API调用用于获取坐标 代码: <?php require_once('../db.php'); $api_key = "somekey"; $sqlQuery = mysql_query("SELECT `County` FROM `table`"); $ch = curl_init(); /* Fetch county */ while($
<?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\u file\u contents()
- 将
添加到php.ini中并没有奏效allow\u url\u fopen=on
- 看起来像是我的,所以这不应该是问题所在
- 我尝试手动转到API调用,得到一个显示正确JSON数据的网页
- SQL查询似乎也可以正常工作
<?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);
?>
- 我尝试在中回显
和$obj->status
在else声明中,没有显示任何内容。因此,$obj->results->location->lat
似乎为空$obj
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);
我在您的示例中看到了两个潜在问题:
curl\u-exec
如果请求失败可能返回false
,json\u-decode
如果解码失败可能返回null
(因为它从curl\u-exec
接收到false
)。除了捕获这些错误案例外,还可以触发“跟踪子弹”-var_dump
语句,以确认这些返回值是您期望的值。要节省使用Guzzle编写和调试HTTP客户端的时间,请执行以下操作: