0

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!

0

1 Answer 1

1

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].


This is the structure (from 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

Sign up to request clarification or add additional context in comments.

1 Comment

@Oren, no problems, I'm glad to help. It's easier to miss them when there is only one item in the array...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.