簡體   English   中英

在獲取Google API數據時,cURL無法正常工作

[英]cURL not working while fetching Google API data

所以,我正在嘗試使用cURL獲取API數據,但是我從下面的代碼中的else語句中得到消息“fail”。 API調用是用於獲取坐標的Google地理編碼

代碼:

 <?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查詢似乎也正常工作。

編輯:

  • 我嘗試在else語句中回顯$obj->status$obj->results->location->lat ,沒有顯示任何內容。 所以$obj似乎是NULL

在驗證證書時它似乎失敗,您可以禁用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM