I am following a tutorial that uses a foreach statement to loop through a json file. Of course in the example I am following this works fine, but I can't seem to get it to work on my version. I think that the error is indicating that I am not actually passing an array. Does that mean the issue is in the json file? Or is there a syntax issue?
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\loops\json_example.php on line 27
JSON FILE: movies.json
{ //json object
"movies": [ //movies = array
{
"title": "The Godfather",
"year": "1972",
"genre": "Drama",
"director": "Francis Ford Copolla"
},
{
"title": "Superbad",
"year": "2007",
"genre": "Comedy",
"director": "Greg Mottola"
},
{
"title": "The Departed",
"year": "2006",
"genre": "Drama",
"director": "Martin Scorsese"
},
{
"title": "Saving Private Ryan",
"year": "1998",
"genre": "Action",
"director": "Steven Spielberg"
},
{
"title": "The Expendables",
"year": "2010",
"genre": "Action",
"director": "Sylvester Stallone"
}
]
}
PHP CODE: json_example.php
<?php
$jsondata = file_get_contents("movies.json"); #set variable, function "file_get_contents" grabs everything in the file. can also use with a website is url is within () to insert entire site.
$json = json_decode($jsondata, true); #decodes json so that we can parse it
?>
<!DOCTYPE html>
<html>
<head>
<title>JSON Example</title>
</head>
<body>
<div id="container">
<h1>My Favorite Movies</h1>
<ul>
<?php
foreach($json['movies'] as $key => $value) {
echo '<h4>'.$value['title'].'</h4>';
echo '<li>Year: '.$value['year'].'</li>';
echo '<li>Genre: '.$value['genre'].'</li>';
echo '<li>Director: '.$value['director'].'</li>';
}
?>
</ul>
</div>
</body>
</html>
Please excuse my comment notes, I am still learning.