【问题标题】:how to parse JSON google maps JSON in php如何在 php 中解析 JSON 谷歌地图 JSON
【发布时间】:2012-07-07 11:18:33
【问题描述】:

如何在 php 中解析 JSON google maps JSON

我已经在xml中做了,但是坐标驱动方向不完整,因为我用JSON得到,我们如何在php中用JSON得到所有坐标驱动?

如果我们使用 xml

$xml = simplexml_load_file('http://maps.googleapis.com/maps/api/directions/xml?origin='.$origin.'&destination='.$dest.'&sensor=false');
$startlat = $xml->xpath("/DirectionsResponse/route/leg/step/start_location/lat");
$startlng = $xml->xpath("/DirectionsResponse/route/leg/step/start_location/lng");
$distanceeach = $xml->xpath("/DirectionsResponse/route/leg/step/distance/value");
$distance = $xml->xpath("/DirectionsResponse/route/leg/distance/value");

但是如何处理 json? 如果我们使用 xml,我希望我的变量 $startlat、$startlng 等包含相同的值

【问题讨论】:

    标签: php xml json parsing google-maps


    【解决方案1】:

    你可以检索JSON格式的数据,然后使用json_decode()函数来构建stdClass对象,然后你可以递归遍历对象的属性将其转换为(array) $response这样。

    然后使用 Google Maps API 响应作为数组。您可以继续不转换为数组,并像这样使用stdClass 的对象:

    $response->DirectionsResponse->route->leg->step->start_location->lat;
    

    要获得正确的值,您可以随时var_dump()您的响应对象,看看您想要得到什么。

    希望,这会有所帮助。


    以下是使用 Google Translate API 的 Google JSON 响应的代码...与您需要的基本相同:

    if (!is_null($json = json_decode(file_get_contents($url)))
    {
        return $json->data->translations[0]->translatedText;
    }
    

    就是这样……

    【讨论】:

    • hai @devdRew 你能给我完整的代码吗?我被困在这里:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 2012-05-30
    • 2014-04-06
    相关资源
    最近更新 更多