If you're going to build anything on the web,
chances are you'll run into JSON data.
You'll often receive a response in JSON when requesting data from an API.
It's also a common format for configuration files.
So what makes JSON so popular?.
JSON is an easy way to encode structured data and
transfer that data between systems.
It has simple markup, and when formatted it's fairly easy for humans to read.
It is also easily validated and
transformed natively in most modern languages.
JSON stands for JavaScript Object Notation, but
we don't need to write any JavaScript.
PHP has a handy function for turning JSON objects into PHP objects and arrays.
We can also turn an object or array from PHP into JSON.
Let's give it a try, while I share some of my top programming books.
Open bookstop.,php, again,
I've started by showing the contents of the JSON file and also a sample book.
Let's preview this in a browser.
We can see that the JSON file is clean and easy to read with a collection of books.
These books have different attributes that are clearly defined.
And here's what the sample book looks like.
Let's go back to work spaces and remove the file display and
replace the sample book with the data from the JSON.
The first thing we need to do is get the contents of the JSON file.
Then we'll use the json_decode function to turn this into an object.
We'll assign this to the variable books.
Before I try to use the object I wanna make sure that it's actually set up like I
expect.
If is_object books
collection.
And books.
Should be an array of objects.
Now I can loop through each book and
replace the sample book with the book properties.
Now, let's take a look at this in the browser.
The details that I want are there but some of the descriptions are just too long.
I don't want to display more than 500 characters.
The book description itself is a string, so
we can interact with it just like any other string.
Let's go back to work spaces.
First, I wanna check if the string is less than 500 characters.
Then I'll just show the whole description.
Else I'm going to use substring.
I want to start at the beginning, echo substring
book book description.
To start at the beginning, I use 0.
Then for the endpoint I could just use 500, but
it might cut off in the middle of the word.
Instead I'll use the string position and look for
the next space after 500 characters.
And finally all in the line with three dots.
Let's space this out a little bit.
Now let's go back to the browser.
Great, the books are much more uniform.