【问题标题】:Returning data from Google's Geocoding API with PHP curl使用 PHP curl 从 Google 的地理编码 API 返回数据
【发布时间】:2017-08-16 17:25:10
【问题描述】:

这个问题与另一个回答的问题相似,但是在这种情况下,解决方案是使用国家代码,这对于这种特定用途是不可行的,因为地址是由用户通过输入字段提供的(因此可能不提供国家/地区)。

这是我当前请求的内容

来自 AngularJS 的请求:

function getCoordinatesFromApi(address) {
            addressApiResponse = $http({
                url: 'php/coordinates.php',
                method: 'get',
                params: {
                    address: address
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            });
            return addressApiResponse;
        }

用 PHP 处理的请求:

$api_maps = 'https://maps.googleapis.com/maps/';
$address = urencode($_GET['address']);
$api_key = 'API_key_here';
$url = $api_maps . 'api/geocode/json?address=' . $address . '&key=' . $api_key;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($curl);
curl_close($curl);
echo ($curl_response);

调用此函数时,我始终返回状态为 200 的有效响应,但数据是空字符串。

我已经检查了在 PHP 中构建的 $url 的有效性,没问题,直接在浏览器中访问该 url 会显示一个有效的 API 响应和数据。

我也尝试过使用 Angular 的 $http 方法,它也可以从 API 返回有效响应:

function getCoordinatesFromApi(address) {
            addressApiResponse = $http.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=API_key_here');
            return addressApiResponse;
        }

由于某种原因,只有 curl 方法的行为不符合预期。有人处理过这个问题吗?

【问题讨论】:

    标签: php angularjs curl google-geocoding-api


    【解决方案1】:

    如果你说的是 echo ($curl_response);即使状态为 200 也不返回任何内容,这是因为它是 JSON 编码的!

    请试试这个:

    $decodedresponse = json_decode($curl_response);
    
    //send me what var_dump return so I can hellp you accessing the array!
    echo var_dump($decodedresponse);
    
    
    //You would use as an array DEPENDING ON HOW THE ARRAY IS BUILD OF COURSE
    echo $decodedresponse['response']['lat'];
    echo $decodedresponse['response']['long'];
    

    【讨论】:

    • 我已经尝试过了,但它似乎也不起作用。随着您的更改到位,数据现在返回“NULL”,没有其他内容。
    • $decodedresponse = json_decode($curl_response); // 将 var_dump 返回的内容发送给我,以便我可以帮助您访问数组! echo var_dump($decodedresponse);就这个?
    • 是的,这就是我返回的全部内容。我的 php 现在看起来像这样:$curl_response = curl_exec($curl); curl_close($curl); // echo ($curl_response); $decodedresponse = json_decode($curl_response); echo var_dump($decodedresponse); 进行此调用时,我在 JS 中得到的整个响应是:config:{method: "GET", transformRequest: Array(1), transformResponse: Array(1), jsonpCallbackParam: "callback", paramSerializer: ƒ, …} data:"NULL↵" headers:ƒ (d) status:200 statusText:"OK" __proto__:Object
    • 嗯,我不喜欢 JS,所以对此无能为力。
    【解决方案2】:

    再试一次

    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false
    
    猜你喜欢
    • 2019-01-15
    • 2010-12-24
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    相关资源
    最近更新 更多