如何解析JSON google在php中映射JSON


how to parse JSON google maps JSON in php

如何解析JSON google映射php 中的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呢?我希望我的变量$startlat、$startlng等包含相同的值,如果我们使用xml

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

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

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

为了获得正确的值,您可以始终var_dump()您的响应对象,并查看您想要得到什么。

希望,这有帮助。


以下是使用Google翻译API的Google JSON响应的代码。。。这与您需要的大致相同:

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

就是这样…