JSON (JavaScript Object Notation) is a very lightweight data format widely used for exchanging information between applications.
This means that by using JSON we can create systems or APIs in a specific language, such as PHP, and provide the data without having to worry about which language will consume that data, whether it's JavaScript or any other programming language. That's something amazing!
In this article, we will talk about how to manipulate JSON in PHP. For that, we will discuss the functions aimed at this.
json_encode() - Converting a variable to JSON
The first parameter that this function expects is the variable that will be converted into a JSON string. We usually use this function to convert an array into JSON, but this variable can be any value.
For the first example, we will create a multidimensional array of programming languages. Each item in the array will display the full name and short name of the language. After creating it, we will call the json_encode() function:
<?php
$languages = [
[
"name"=>"PHP 7",
"short_name"=>"PHP"
],
[
"name"=>"JavaScript",
"short_name"=>"JS"
],
[
"name"=>"Vue JS",
"short_name"=>"Vue"
]
];
echo json_encode($languages);
When accessing our file on the server, we see the following result:
Our JSON was correctly displayed in the browser. Pretty simple, right?
We executed this function on a multidimensional array. But what if we have a simple array to convert to JSON? What happens in this case? Let's see now! We will create an array of courses and call the json_encode() function again:
$courses = ['PHP7', 'JavaScript', 'MySQL', 'Vue'];
echo json_encode($courses);
We will see the following result in the browser:
No errors were returned. But notice that the brackets remained. It seems to continue as an array. How could we force it to be an object, using keys, like in the first example? To solve this issue, we can use a very interesting feature of the json_encode() function. This function expects a second parameter, which is the formatting options for the JSON. These options are PHP constants. We can find a complete list of these constants in the PHP documentation. But don’t worry, as we will discuss some of them in this article.
Forcing a JSON to be an object
The first example can force a JSON to be an object. For that, we will use this code:
echo json_encode($courses, JSON_FORCE_OBJECT);
When refreshing the browser, we see the following result:
Now our JSON is indeed in object notation.
There are other options that can help us in specific situations. Let's see some examples.
Converting strings to numbers
Let's create an array that shows the name of several languages and their respective release years:
$languages = [htpp
[
'name'=>'PHP',
'release_year'=>'1994'
],
[
'name'=>'JavaScript',
'release_year'=>'1995'
],
[
'name'=>'SQL',
'release_year'=>'1974'
]
];
When calling the json_encode() function on this variable, we will see the following result:
Our JSON was returned correctly. However, the release year was displayed as a string because it's in quotes. Wouldn't it make more sense if it were displayed as an actual number? To perform this conversion, we can use the JSON_NUMERIC_CHECK option in our code, like this:
echo json_encode($languages, JSON_NUMERIC_CHECK);
Now, when viewing the browser again, we will see the following result:
Perfect! Now the years were returned as actual numbers, without quotes.
Working with URLs in JSON
The next situation we will learn is when we need to work with URLs in JSON. Let's create a new array of courses, which will return the name of the course and its URL:
$courses = [
[
"name"=>"PHP7",
"url"=>"https://www.hcode.com.br/cursos/PHP7"
],
[
"name"=>"JavaScript",
"url"=>"https://www.hcode.com.br/cursos/JSFULL"
],
[
"name"=>"MySQL",
"url"=>"https://www.hcode.com.br/cursos/MYSQL"
],
[
"name"=>"Vue",
"url"=>"https://www.hcode.com.br/cursos/VUE"
]
];
Now, let's perform the encoding of this array:
echo json_encode($courses);
The result will be:
Note that our URLs were displayed with “duplicated” slashes. What happens is that these slashes are being “escaped” by JSON. To solve this issue, we will use the JSON_UNESCAPED_SLASHES constant:
echo json_encode($courses, JSON_UNESCAPED_SLASHES);
The result now will be the following:
Excellent, our URLs are much easier to read!
A tip for visualizing JSON
We can take this moment to share a very cool tip. We are able to read JSON normally. However, if you want a more pleasant visualization of these results, we recommend the JSONView extension, which is available on Google Chrome. With the help of this extension, the JSON we saw above can be displayed as follows:
Much better, isn’t it?
Resolving accentuation issues
Another situation where the constants of the json_encode() function can help us is regarding accentuation. To see this problem in practice, we will use PHP to establish a connection with the MySQL Database and fetch the information of the courses from this Database. For that, we will use the following code:
$connection = new PDO("mysql:dbname=hcode;host=127.0.0.1", "root", "root");
$statement = $connection->prepare('SELECT * FROM courses;');
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
The structure of the courses table looks like this:
Note that the courses in the Database are the same. We only added the phrase “in Practice” to the PHP 7 course.
Let's display the information that PHP fetched from MySQL with this code:
echo json_encode($results);
When we refresh our browser, we see the following result:
The data was displayed correctly. However, since the word “Prática” has an accent, it was converted to a special character. It may be bothersome to see the course name this way. In this case, we can use the JSON_UNESCAPED_UNICODE constant. Our code will change a little and will look like this:
echo json_encode($results, JSON_UNESCAPED_UNICODE);
Now the result will be:
It's much more pleasant, excellent! This is definitely one of the most interesting “tricks” in PHP when working with JSON.
And if we want to combine two constants? For example, considering the last example, how could we convert not just the characters of the data but also not escape the slashes of the URL? To apply more than one constant on the same variable, we can use the | (pipe) sign. The example we just mentioned could look like this:
echo json_encode($results, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
And this way both formatting options would occur in our JSON.
json_decode() - Converting a JSON string into an object or array
If json_encode() converts a variable to JSON, the json_decode() function does exactly the opposite.
The first parameter it expects is a JSON string. By default, this function converts JSON into an object. If we want to convert it into an array, just pass the boolean true as the second parameter.
To see this function “in action”, we will continue using the last example. The “photos” column of our courses table is of JSON type, a novelty of MySQL 8. In fact, we talked about other novelties in this version in Hcode Café #19.
Imagine we want to display all photos of the courses in the browser. We will use the json_decode() function for that.
Our code will look like this:
foreach ($results as $row) {
$photos = json_decode($row['photos'], true);
foreach ($photos as $photo) {
echo "<img src=" . $photo . " />";
}
}
Explaining: we performed a foreach() on the information returned by the Database and accessed the data of each of the courses. Then we converted only the “photos” column into an array and stored its value in the $photos variable. Finally, we performed another foreach() on this variable to display each of the images individually using an tag. The result will be:
Perfect! Each of the images was correctly displayed in the browser! Imagine how many situations this function can assist us with.
json_last_error() - Returning possible errors
We know that one of the most common things in programming is bugs, and this also happens with JSON. If there is a bug, we can use the json_last_error() function to find out what went wrong.
This function returns an integer. We can say that each of these numbers is like an “error code.” They can also be accessed through other PHP constants.
A complete list of possible constants can be found in the PHP documentation.
Conclusion
In this article, we saw many situations where JSON functions can help us. Knowing how to manipulate this JavaScript notation is a necessary skill for primarily achieving communication between servers.
If you want to learn more about JSON in PHP, applied in real projects, don’t forget to take our Complete Course on PHP 7.
We hope you enjoyed it and see you in the next article :)