Google Maps PHP CURL问题"您的客户发出了格式错误或非法的请求.这就是我们所知道的."

The*_*ter 4 php curl google-maps google-api

我有一个函数,它使用CURL和Google Maps API返回地址的坐标.

代码如下:

function get_coordinates($address_string) {

    $address = urlencode($address_string);
    $url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . $address . "&key=" . $api_key;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $response_a = json_decode($response);
    $status = $response_a->status;

    return $response;

}
Run Code Online (Sandbox Code Playgroud)

代码适用于我和我使用它的99%的Web服务器 - 但对于大约1%的服务器,Google返回错误消息:

Your client has issued a malformed or illegal request. That’s all we know.
Run Code Online (Sandbox Code Playgroud)

我已经检查过,Google API密钥是正确的,启用了PHP CURL,PHP版本与正在处理的PHP版本相匹配.

任何人都可以想到可能导致谷歌返回此消息的任何其他事情吗?

小智 17

由于您的$ address变量具有空格的地址,请使用str_replace并用+号替换空格.

它会工作,我面临同样的问题并以这种方式修复.