将 JSON 值转换为 PHP 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16638758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:29:43  来源:igfitidea点击:

Convert JSON value to PHP string

phpjsongoogle-mapsgoogle-maps-api-3

提问by

Need to get the value "distance" "text" from the Google Maps API, and convert it into a PHP string.

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

For example, https://maps.googleapis.com/maps/api/distancematrix/json?origins=TN222AF&destinations=tn225dj&mode=bicycling&language=gb-FR&sensor=false&units=imperialgives us:

例如,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"
}

How would the value "3.0 mi" be changed into a PHP variable from this JSON feed?

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

Many thanks!

非常感谢!

采纳答案by 7stud

$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

回答by Dory Zidon

Thanks Dory Zidon, I achieved this in the end and it solved my problem:

感谢 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;
?>