【问题标题】:Convert JSON value to PHP string将 JSON 值转换为 PHP 字符串
【发布时间】:2013-05-14 09:01:14
【问题描述】:

需要从 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 变量?

非常感谢!

【问题讨论】:

    标签: php json google-maps google-maps-api-3


    【解决方案1】:

    【讨论】:

      【解决方案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;
      ?>
      

      【讨论】:

        【解决方案3】:
        $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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-04-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-29
          • 2018-06-28
          相关资源
          最近更新 更多