没有带有地址的输出。这个PHP代码有什么问题?有什么解决办法吗?
感谢
<?php
$str = "Street 1 ZIP City";
$adr = $str;
$url = "http://maps.googleapis.com/maps/api/geocode/json?adress=$adr&sensor=false";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_ENCODING, "");
$curlData = curl_exec($curl);
curl_close($curl);
$address = json_decode($curlData);
print_r($address);
?>
您的请求字符串中有一个拼写错误:adress
而不是address
。正确的请求字符串是:
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
此外,在将参数粘贴到请求字符串之前,您最好使用 PHP 的 urlencode()
函数来$adr
参数。
我已经复制并粘贴了您的代码,其中包含之前列出的更改,即我有:
$str = "Street 1 ZIP City";
$adr = urlencode($str);
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_ENCODING, "");
$curlData = curl_exec($curl);
curl_close($curl);
$address = json_decode($curlData);
print_r($address);
对于此示例,我的浏览器中的输出是:
stdClass Object
(
[results] => Array
(
[0] => stdClass Object
(
[address_components] => Array
(
[0] => stdClass Object
(
[long_name] => 1st Street
[short_name] => 1st St
[types] => Array
(
[0] => route
)
)
[1] => stdClass Object
(
[long_name] => Rock Hill
[short_name] => Rock Hill
[types] => Array
(
[0] => locality
[1] => political
)
)
[2] => stdClass Object
(
[long_name] => York
[short_name] => York
[types] => Array
(
[0] => administrative_area_level_2
[1] => political
)
)
[3] => stdClass Object
(
[long_name] => South Carolina
[short_name] => SC
[types] => Array
(
[0] => administrative_area_level_1
[1] => political
)
)
[4] => stdClass Object
(
[long_name] => United States
[short_name] => US
[types] => Array
(
[0] => country
[1] => political
)
)
[5] => stdClass Object
(
[long_name] => 29730
[short_name] => 29730
[types] => Array
(
[0] => postal_code
)
)
)
[formatted_address] => 1st Street, Rock Hill, SC 29730, USA
[geometry] => stdClass Object
(
[bounds] => stdClass Object
(
[northeast] => stdClass Object
(
[lat] => 34.9241861
[lng] => -81.01329
)
[southwest] => stdClass Object
(
[lat] => 34.923073
[lng] => -81.0157245
)
)
[location] => stdClass Object
(
[lat] => 34.923658
[lng] => -81.014494
)
[location_type] => GEOMETRIC_CENTER
[viewport] => stdClass Object
(
[northeast] => stdClass Object
(
[lat] => 34.924978530291
[lng] => -81.013158269708
)
[southwest] => stdClass Object
(
[lat] => 34.922280569709
[lng] => -81.015856230292
)
)
)
[partial_match] => 1
[types] => Array
(
[0] => route
)
)
[....more addresses here..]
)
[status] => OK
)