Posted under » PHP on 24 Oct 2018
Now that we have encoded to JSON. It's time to decode it back for viewing.
The encoded file will look something like this.
[{"author_name":"Machida S, Chen HY","title":"Molecular Arabidopsis thaliana SERRATE"},{"author_name":"Yang X, Tan SH","title":"RNA silencing suppression by NS3 protein of Tenuivirus"}]
$url = 'http://heh.com/pubjson.php'; $data = file_get_contents($url); // put the contents of the file into a variable $king = json_decode($data, true); // true must be on // echo $king[0]->author_name; if you want to see the first row foreach ($king as $character) { echo "<p>".$character['author_name']. "\n"; }
This is the easiest way to loop the array. If you pass "true" as the argument in json_decode(), the data becomes an associative array instead of an object. This means we’ll be using square bracket notation[] instead of the skinny arrow->.
However, if you need to have more control on how many rows to display, you might want to use this looping method.
$count= count($king); for ($i=0; $i < $count; $i++) { echo $king[$i]["author_name"] . "<br>"; }
You can also do association JSON like
{ "FIFA_World_Cup_finals": [ { "Year": "2018", "data": { "Winner": "France", "Score": "4-2", "Runner-up": "Croatia" } }, { "Year": "2014", "data": { "Winner": "Germany", "Score": "1-0", "Runner-up": "Argentina" } }, { "Year": "2010", "data": { "Winner": "Spain", "Score": "1-0", "Runner-up": "Netherlands" } } ] }
You can iterate them using $jsonIterator
<¿php $JSON = file_get_contents("input.json"); $jsonIterator = new RecursiveIteratorIterator( new RecursiveArrayIterator(json_decode($JSON, TRUE)), RecursiveIteratorIterator::SELF_FIRST); foreach ($jsonIterator as $key => $val) { if(!is_array($val)) { if($key == "Year") { print "
"; } print $key." : ".$val . "
"; } } ?>