Forgive me for the simplicity of this question but I am brand new to working with API's and JSON. But I have a JSON file and I want to print out the "text" value of "duration". How can I do that?
{
"destination_addresses" : [ "San Francisco, CA, USA" ],
"origin_addresses" : [ "Seattle, WA, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "808 mi",
"value" : 1299998
},
"duration" : {
"text" : "12 hours 27 mins",
"value" : 44846
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I am trying to do it using:
$url = 'https://maps.googleapis.com/maps/......'
$content = file_get_contents($url);
$json = json_decode($content, true);
echo $json['rows']['elements']['duration']['text'];
Many thanks!
You should do it like this:
echo $json['rows'][0]['elements'][0]['duration']['text'];
Output:
12 hours 27 mins
Notice that in the json
, you have what marks new arrays [
, so you forgot to use [SOME_NUMBER]
.
print_r($json);
):Array
(
[destination_addresses] => Array
(
[0] => San Francisco, CA, USA
)
[origin_addresses] => Array
(
[0] => Seattle, WA, USA
)
[rows] => Array
(
[0] => Array
(
[elements] => Array
(
[0] => Array
(
[distance] => Array
(
[text] => 808 mi
[value] => 1299998
)
[duration] => Array
(
[text] => 12 hours 27 mins
[value] => 44846
)
[status] => OK
)
)
)
)
[status] => OK
)
You can also use it as object. It would be like this:
$json = json_decode($content); // without true
echo $json->rows[0]->elements[0]->duration->text;
Output:
12 hours 27 mins