将Google API JSON响应获取到单独的php变量中


Getting a Google API JSON response into individual php variables

我有这个网页,它需要两个邮政编码,并得到距离以及谷歌吐出的其他东西。

代码:

$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$postcode1&destinations=$postcode2&mode=bicycling&language=en-EN&sensor=false";
$data = @file_get_contents($url);
$result = json_decode($data, true);
print_r($result);

结果如下:

{
   "destination_addresses" : [ "Pound Rd, Oldbury B68 8NE, UK" ],
   "origin_addresses" : [ "Vyse St, Birmingham B18 6NE, UK" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "10.4 km",
                  "value" : 10384
               },
               "duration" : {
                  "text" : "36 mins",
                  "value" : 2133
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

我自己是JSON的新手,所以如果这听起来很愚蠢,请原谅。我试过很多次了。最接近的是

echo $result['destination_addresses'][0];

返回目的地址。我想知道如何单独获得所有内容,特别是距离文本。

提前感谢!

Jake32

解决方案如下:-

echo "Destination Address=".$result['destination_addresses'][0]."<br>";
echo "Origin Address=".$result['origin_addresses'][0]."<br>";
echo "Distance text=".$result['rows'][0]['elements'][0]['distance']['text']."<br>";