简体   繁体   English

在获取Google API数据时,cURL无法正常工作

[英]cURL not working while fetching Google API data

So, I'm trying to fetch API-data using cURL , but I get the message "fail" from the else-statement in the code below. 所以,我正在尝试使用cURL获取API数据,但是我从下面的代码中的else语句中得到消息“fail”。 The API call is Google geocode for fetching coordinates. API调用是用于获取坐标的Google地理编码

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);
?> 
  • I intended to use get_file_contents() earlier but it seems like my hosting has deactivated that function. 我打算先使用get_file_contents() ,但似乎我的托管已停用该功能。
  • Adding allow_url_fopen = on to php.ini didn't do the trick. allow_url_fopen = on添加到php.ini并没有办法解决问题。
  • It seems like my hosting allows cURL , so that shouldn't be the problem. 好像我的托管允许cURL ,所以这应该不是问题。
  • I've tried to manually go to the API-call and I get a webpage showing the correct JSON-data. 我试图手动转到API调用,然后我得到一个显示正确JSON数据的网页。
  • The SQL-query seems to be working fine too. SQL查询似乎也正常工作。

Edit: 编辑:

  • I tried echoing $obj->status and $obj->results->location->lat in the else-statement, nothing showed up. 我尝试在else语句中回显$obj->status$obj->results->location->lat ,没有显示任何内容。 So $obj seems to be NULL 所以$obj似乎是NULL

It seems it fails while verifying certificate, you could disable CA verification 在验证证书时它似乎失败,您可以禁用CA验证

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM