3

需要从 Google Maps API 中获取值 "distance" "text",并将其转换为 PHP 字符串。

例如,https ://maps.googleapis.com/maps/api/distancematrix/json?origins=TN222AF&destinations=tn225dj&mode=bicycling&language=gb-FR&sensor=false&units=imperial给我们:

{
   "destination_addresses" : [ "New Town, Uckfield, East Sussex TN22 5DJ, UK" ],
   "origin_addresses" : [ "Maresfield, East Sussex TN22 2AF, UK" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "3.0 mi",
                  "value" : 4855
               },
               "duration" : {
                  "text" : "22 mins",
                  "value" : 1311
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

如何将值“3.0 mi”从这个 JSON 提要更改为 PHP 变量?

非常感谢!

4

3 回答 3

2

json_decode是你的朋友和答案:)

http://php.net/manual/en/function.json-decode.php

于 2013-05-19T19:49:41.983 回答
2

感谢 Dory Zidon,我最终实现了这一点,它解决了我的问题:

<?php
    $q = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=TN222AF&destinations=tn225dj&mode=bicycling&language=gb-FR&sensor=false&units=imperial"; 
    $json = file_get_contents($q);
    $details = json_decode($json);
    $distance=$details->rows[0]->elements[0]->distance->text;
    echo $distance;
?>
于 2013-05-19T19:55:14.847 回答
1
$json = <<<END_OF_JSON
{
   "destination_addresses" : [ "New Town, Uckfield, East Sussex TN22 5DJ, UK" ],
   "origin_addresses" : [ "Maresfield, East Sussex TN22 2AF, UK" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "3.0 mi",
                  "value" : 4855
               },
               "duration" : {
                  "text" : "22 mins",
                  "value" : 1311
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}
END_OF_JSON;

$arr = (json_decode($json, true));
echo $arr["rows"][0]["elements"][0]["distance"]["text"];

--output:--
3.0 mi
于 2013-05-19T19:58:53.693 回答