I am using the following code to return some api information:
$jsonfile = file_get_contents($url);
$jsondata = json_decode($jsonfile);
print_r($jsondata->routes[0]->legs[0]->distance);
This displays the following data on the webpage:
stdClass Object ([text] => 91.4 mi[value] => 147088 )
What I need to know, is how to convert the value field (e.g. [value]=147088
) to a variable that I can save within my database, e.g. how do I get
$value = xxxxx
Hello and welcome to the community.
Use the code below:
<?php
$jsonfile = file_get_contents($url);
$jsondata = json_decode($jsonfile, true);
extract($jsondata);
How this code works:
1- I added a second parameter to the json_decode()
function which is a Boolean and if it is true it will return an array instead of an object.
2- extract()
function will assign a array value to its key as a variable. Like:
<?php
$my_array = ["firstname" => "Adnan", "lastname" => "Babakan"];
extract($my_array);
// $firstname = "Adnan";
// $lastname = "Babakan";
I hope this was your answer.