The ease of working with JSON is one of the main reasons
it has become such a popular format for sharing data on the web.
We can take any object or array from PHP and turn it into a JSON
object that can then be shared without needing to rely on a particular language.
I can share the JSON for my recommendations and
they can be easily read using Python or any other language.
Communication is what has made the Internet such a powerful force.
Let's create another file in the inc directory.
We'll name this one
write_json [SOUND].
We'll start by creating an array for the new book.
[SOUND] This time,
we'll be using the FormData from the Add book form.
And our array will be an associative array.
Our title will be filter_
input(INPUT_POST, 'title, and
FILTER_SANITIZE_STRING..
We'll copy this for link, book, image, book description,
pages, author, ISBN, rating and publish date.
Link, [SOUND] and
this will be a URL.
Our book_image_url, [SOUND] which will also be a URL.
[SOUND]
Our book_description,
[SOUND] number
of pages [SOUND]
which will be
a NUMBER_INT.
[SOUND] author_name,
[SOUND] isbn [SOUND]
which will be
a NUMBER_INT.
[SOUND] Our
average_rating [SOUND]
which will be
a number float.
And finally book_published.
[SOUND] And this will
also be a NUMBER_INT.
Once again, we need to get the contents of the JSON file and
use the JSON decode function to turn it into an object.
We'll be using this file a couple of times.
So we'll set this up as a variable.
Our file = '
../data/json/top_programming_books.json.
books
=json_decode(file_get_contents
and the file.
Next, let's make sure the object is as expected.
Is_object($books->collection->books,
and the first array item.
Now we can add the new book to our book collection.
Next, we can use the json_encode function to turn our object back into JSON.
Before we actually write this back to our file,
let's take a quick look at the JSON itself, by displaying it to the browser.
Make sure we use the pretags.
And let's preview this in the browser.
We're going to add a book.
I'm going to pull the information from good reads.
There's no ISBN, so I'll leave that blank.
And the publish date was 2016.
I wanna pull the smaller image.
And let's add the book.
We have the json but it's not the prettiest.
Let's add a couple options to our json encode function.
See the notes associated with this video for more available options.
We'll use
JSON_PRETTY_PRINT |
JSON_UNESCAPED_SLASHES.
Now, let's preview this again.
Much better.
Let's write this back to our file and finish by redirecting to the books page.
Let's comment out the echo.
file_put_contents, file and our json.
Header is location: /books.php.
Let's check out the final functionality in the browser.
We fill out a form, submit it, and now our book shows up.