Last active
February 19, 2024 21:43
-
-
Save daveh/4aef69186bd99a99aa31409844a24a99 to your computer and use it in GitHub Desktop.
Parse JSON in PHP | How to validate and process nested JSON data (code to accompany https://youtu.be/KZW2jtUhKZA)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"title": "Fairy Tales", | |
"pages": 100, | |
"price": 3.99, | |
"available": true, | |
"language": null, | |
"categories": ["children", "fiction"], | |
"author": { | |
"firstname": "Hans Christian", | |
"surname": "Andersen" | |
} | |
}, | |
{ | |
"title": "Gardening", | |
"pages": 250, | |
"price": 14.50, | |
"available": false, | |
"language": "en", | |
"categories": ["education", "non-fiction"], | |
"author": { | |
"firstname": "Teresa", | |
"surname": "Green" | |
} | |
}, | |
{ | |
"title": "Space", | |
"pages": 55, | |
"price": 3.00, | |
"available": true, | |
"language": "en", | |
"categories": ["non-fiction"], | |
"author": { | |
"firstname": "Teresa", | |
"surname": "Green" | |
} | |
} | |
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$contents = file_get_contents('books.json'); | |
try { | |
$data = json_decode($contents, | |
flags: JSON_THROW_ON_ERROR | JSON_OBJECT_AS_ARRAY); | |
} catch (JsonException $e) { | |
exit($e->getMessage()); | |
} | |
/* | |
if (json_last_error() !== JSON_ERROR_NONE) { | |
echo json_last_error_msg(); | |
} | |
*/ | |
var_dump($data[0]['title']); | |
var_dump($data[1]['pages']); | |
var_dump($data[0]['author']['firstname']); | |
echo '<pre>'; | |
print_r($data); | |
echo '</pre>'; | |
?> | |
<h1>Books</h1> | |
<?php foreach ($data as $book): ?> | |
<h2><?= $book['title'] ?></h2> | |
<p>by <?= $book['author']['firstname'] ?> | |
<?= $book['author']['surname'] ?></p> | |
<p><?= implode(', ', $book['categories']) ?></p> | |
<table> | |
<thead> | |
<tr> | |
<th>Pages</th> | |
<th>Price</th> | |
<th>Available</th> | |
<th>Language</th> | |
</tr> | |
</thead> | |
<tbody> | |
<tr> | |
<td><?= $book['pages'] ?></td> | |
<td>£<?= number_format($book['price'], 2) ?></td> | |
<td><?= $book['available'] ? 'yes' : 'no' ?></td> | |
<td><?= $book['language'] ?? 'unknown' ?></td> | |
</tr> | |
</tbody> | |
</table> | |
<hr> | |
<?php endforeach; ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment