Google地理编码服务返回错误400错误请求

Chu*_*huy 11 curl google-geocoder

我一直试图从谷歌的地理编码服务获得json回应.我正在使用PHP.我正在尝试fopen,然后我在另一个stackoverflow问题中读到我应该使用file_get_contents,但是也没有用.然后我一直在搜索并在另一个论坛中找到一个人,如果我使用CURL,我会更好的解决方案,所以我改变了我的代码并且无法正常工作.在所有情况下,我收到"错误400:错误请求.您的客户发出了格式错误或非法的请求."

我的代码是这样的:

$jsonUrl = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $cityName . "&sensor=false";

    $geocurl = curl_init();
    curl_setopt($geocurl, CURLOPT_URL, $jsonUrl);
    curl_setopt($geocurl, CURLOPT_HEADER,0); //Change this to a 1 to return headers
    curl_setopt($geocurl, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
    curl_setopt($geocurl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($geocurl, CURLOPT_RETURNTRANSFER, 1);

    $geofile = curl_exec($geocurl);
Run Code Online (Sandbox Code Playgroud)

然后我打印内容并收到错误消息.

有任何想法吗?

非常感谢你.

Chu*_*huy 20

好吧,我明白了.

我的$ cityName变量是这样的:

$cityName = "Monterrey, NL";
Run Code Online (Sandbox Code Playgroud)

逗号和"NL"之间的空白区域.我使用str_replace更改""为"+"并获得一个有效的URL,如文档中所示:

http://code.google.com/intl/es/apis/maps/documentation/geocoding/

问候和非常感谢您的帮助!

  • 或者你可以将所有变量包装在`urlencode()`中 (5认同)