How to get data from an external JSON file – PHP

1
2
3
4
5
6
//assign the file contents to the array myJsonInput
$myJsonInput = file_get_contents("/Path/test.json");
//Use json_decode to "Take a JSON encoded string and convert it into a PHP variable"
$json_arr=json_decode($myJsonInput,true);
//Create an empty array, $myLinks, to put the links in (in this example of pinboard bookmarks)
$mylinks = array();

The test.json file is of the form:

1
{"data":[{"description": "blah blah", "href":"http://google.com", "tags":"Search, News"},{"description": "more blah", "href":"http://nyt.com", "tags":"News"}]}
1
2
3
4
5
6
7
8
9
10
//Now, loop through the array to extract k:v pairs:
//Note that "data" is the name of the container in the json file
//The variable $link is basically a row of data
foreach ($json_arr['data'] as $link) 
{
	//Create an associative array ('hash', 'dictionay') pairing the description with the hyperlink in this case
    $mylinks[$link['description']] = $link['href'];
    //Put the results in a table:
    echo '<tr><td>', '<a href="', $link['href'], '">',$link['description'], '</a>', '</td><td>', $link['tags'],'</td></tr><p>';
}

Links
json_decode

Random Day of Week Calculator

Random Date generator


Answer

Refresh this page

References
  1. Link
  2. Link