Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON value to PHP string

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

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

{
   "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?

Many thanks!


2 Answers

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

<?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;
?>
$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
like image 24
7stud Avatar answered Oct 26 '25 17:10

7stud