简体   繁体   中英

How to extract a value from this JSON response

I am using the file_get_contents() function in PHP to retrieve the contents on a page containing a JSON response. However, I am struggling to get the "text" data.

$response = file_get_contents(someData)

I can use var_dump(json_decode($response)); to show the data, however, I am trying to get the data from the "text" field only within duration.

So far I have tried

  • $response[0];
  • $response->rows[0]->elements[0]->duration[0]->text;

But I cannot seem to get the data. I have pasted the response below

{
   "destination_addresses" : [ "Manchester, UK", "Liverpool, Merseyside, UK" ],
   "origin_addresses" : [ "London, UK" ],
   "rows" : [
  {
     "elements" : [
        {
           "distance" : {
              "text" : "335 km",
              "value" : 335444
           },
           "duration" : {
              "text" : "3 hours 36 mins",
              "value" : 12955
           },
           "status" : "OK"
        },
        {
           "distance" : {
              "text" : "354 km",
              "value" : 354415
           },
           "duration" : {
              "text" : "3 hours 43 mins",
              "value" : 13387
           },
           "status" : "OK"
        }
     ]
  }
     ],
   "status" : "OK"
}
$response = json_decode(file_get_contents(someData));

$text = $response->rows[0]->elements[0]->duration->text;

var_dump($text);

Your only mistake was a [0] after duration .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM