0

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をどうするか?xmlを使用する場合、変数$ startlat、$startlngなどに同じ値が含まれるようにします

4

1 に答える 1

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

それでおしまい...

于 2012-07-07T12:28:55.087 に答える