如何解析PHP中的JSON谷歌地图JSON

时间:2012-07-07 11:18:34

标签: php xml json parsing google-maps

如何解析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? 我希望我的变量$ startlat,$ startlng等,如果我们使用xml

,则包含相同的值

1 个答案:

答案 0 :(得分:1)

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

然后将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;
}

就是这样......