2012-07-07 66 views
0

如何解析JSON谷歌地圖JSON在PHP如何解析JSON谷歌地圖JSON在PHP

我必須做的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

您可以JSON格式檢索數據,然後使用json_decode()功能來構建stdClass對象,那麼你可以遞歸穿行對象的屬性將其轉換爲(array) $response

然後使用Google Maps API響應作爲數組。您可以爲沒有轉換爲數組進行,並使用stdClass對象是這樣的:

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

爲了讓您可以隨時var_dump()你響應對象正確的價值觀,看你想要得到什麼。

希望,這有助於。


這裏是從谷歌谷歌使用JSON響應轉換代碼API ...這是大致相同的,因爲你需要:

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

就是這樣......

+0

你可以給我一個提示? – sephtian 2012-07-08 23:31:50

+0

我用編碼快照編輯了我的答案... – devdRew 2012-07-10 06:18:31

+0

hai @devdRew你能給我完整的代碼嗎?我卡在這裏:( – sephtian 2012-07-27 09:22:32