Convert JSON value to PHP string
27,756
Solution 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
Solution 2
json_decode is your friend and answer :)
http://php.net/manual/en/function.json-decode.php
Author by
Admin
Updated on July 09, 2022Comments
-
Admin almost 2 years
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!