通过PHP中的GOOGLE MAPS GEOLOCATION API获取响应,输出采用JSON格式

时间:2017-07-21 01:09:48

标签: php arrays json google-maps google-geolocation

我一直在寻找答案,没有找到答案。我正在使用谷歌地图地理位置api来显示来自Lat,Long的地址。我只需要显示选择性数据,例如:" formatted_address" 来自数组。这是我试图在PHP中显示响应的代码:

$file_contents = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=31.334097,74.235875&sensor=false", true);
$data = json_decode($file_contents, true);

foreach($data as $output => $var) {
    echo $var;
}

这是回复:[https://maps.googleapis.com/maps/api/geocode/json?latlng=31.334097,74.235875]

这是我得到的输出:

  

注意 C:\ xampp \ htdocs \ bikewala \ myaccount \ index.php 中的数组到字符串转换 176
  ArrayOK

当我尝试使用此代码访问数组的任何组件时:

$file_contents = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=31.334097,74.235875&sensor=false", true);
$data = json_decode($file_contents, true);

foreach($data as $output => $var) {
    echo $var['formatted_address'];
}

我收到此错误:

  

注意:未定义的索引: C:\ xampp \ htdocs \ bikewala \ myaccount \ index.php 中的formatted_address 176
  
  警告:非法字符串偏移&#39; formatted_address&#39;在 C:\ xampp \ htdocs \ bikewala \ myaccount \ index.php 176 上<   0

我在这里做错了什么?

提前致谢!

1 个答案:

答案 0 :(得分:1)

而不是echo(在你的第一个代码部分中)使用print_r($ var)

$file_contents = 
file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?
latlng=31.334097,74.235875&sensor=false", true);
$data = json_decode($file_contents, true);

foreach($data as $output => $var) {
   print_r($var);
}

这将允许您查看您想要的值的路径

您可以使用此代码访问您想要的确切值

$file_contents = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?
latlng=31.334097,74.235875&sensor=false", true);
$data = json_decode($file_contents, true);

$formatted_address = $data['results']['0']['formatted_address'];
echo $formatted_address;