【问题标题】:Getting response from GOOGLE MAPS GEOLOCATION API in PHP, the output is in JSON从 PHP 中的 GOOGLE MAPS GEOLOCATION API 获取响应,输出为 JSON
【发布时间】:2017-12-26 21:37:55
【问题描述】:

我一直在到处寻找答案,没有找到。我正在使用谷歌地图地理定位 api 来显示经纬度的地址。我只需要显示选择性数据,例如: "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.php176
数组确定

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

$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 行

警告C:\xampp\htdocs\bikewala\myaccount\index.php 中的非法字符串偏移 'formatted_address' 在第 176 行

我在这里做错了什么?

提前致谢!

【问题讨论】:

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


    【解决方案1】:

    使用 print_r($var) 代替 echo(在您的第一个代码部分中)

    $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;
    

    【讨论】:

    • 完全没问题:)
    猜你喜欢
    • 2018-09-14
    • 2017-06-01
    • 1970-01-01
    • 2012-03-16
    • 2016-10-22
    • 2013-07-15
    • 1970-01-01
    • 2017-12-29
    • 2020-08-11
    相关资源
    最近更新 更多