【发布时间】:2016-10-17 22:08:00
【问题描述】:
所以,我正在尝试使用 cURL 获取 API 数据,但我从下面代码中的 else 语句中得到消息“失败”。 API 调用是 Google geocode 用于获取坐标。
代码:
<?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 并没有解决问题。 - 好像是我的hosting allows cURL,所以这应该不是问题。
- 我尝试手动转到 API 调用,然后我得到一个显示正确 JSON 数据的网页。
- SQL 查询似乎也运行良好。
编辑:
- 我尝试回显
$obj->status和$obj->results->location->latelse 语句,什么也没出现。所以$obj似乎是 NULL
【问题讨论】:
-
我在您的示例中看到两个潜在问题:
curl_exec可能会在请求失败时返回false,json_decode可能会在解码失败时返回null(因为它从curl_exec)。除了捕获这些错误情况之外,触发“跟踪子弹”(var_dump语句)来确认这些返回值是您所期望的,这将是很有价值的。 -
为了节省使用 Guzzle 编写和调试 HTTP 客户端的时间:docs.guzzlephp.org/en/latest
标签: php json api google-maps curl