问题描述
当我尝试执行下面的代码时,它不起作用。
$json = file_get_contents('https://maps.google.com/maps/api/geocode/json?address=R%20GRANJAO,%2021&sensor=false&key=MYAPIHERE');
var_dump($json);
上面的代码返回“ZERO_RESULTS”。
示例如下:
当然,我使用的是有效的 API,因为大多数地址都有效,但有一些地址无效,就像这个例子一样。
我也尝试使用 urlencode(),但似乎不是这里的问题。
解决方法
我看到有必要添加标题设置“accept-language”。
$url = "https://maps.google.com/maps/api/geocode/json?address=".urlencode($address)."&sensor=false&key=$apiKey";
$header = array('Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3');
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$response = json_decode($json,true);
这解决了问题!