所以,我试图使用cURL获取api数据,但从下面代码中的else语句中得到消息“fail”。
获取坐标的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()的,但似乎我的主机已经停用了这个功能。
在php.ini中添加allow_url_fopen = on并没有起到作用。
好像是我的,所以这不应该是问题所在。
我尝试手动转到api调用,得到一个显示正确json数据的网页。
sql查询似乎也运行得很好。
编辑:
我试着在
其他的声明,什么也没出现。所以$obj->status似乎是空的

最佳答案

验证证书时似乎失败,您可以禁用CA验证
要关闭证书验证(用于对等验证和主机验证),请设置以下选项:

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);

07-24 09:51
查看更多