iDevie
September 2021
M T W T F S S
« Aug    
 12345
6789101112
13141516171819
20212223242526
27282930  

Categories


JSON, short for JavaScript Object Notation, is a common lightweight format for storing and exchanging information. As the name suggests, it was initially derived from JavaScript but it is a language-independent format for storing information. A lot of languages like PHP now implement functions to read and create JSON data.

This tutorial will teach you how to read a JSON file and convert it to an array in PHP. Learn how to parse JSON using the json_decode() and json_encode() functions.

Reading JSON From a File or String in PHP

Let’s say you have a file which contains information in JSON format. How do you access and store it in PHP?

First, you need to get the data from the file into a variable by using file_get_contents(). Once the data is in a string, you can call the json_decode() function to extract information from the string. Keep in mind that JSON simply provides a way to store information as a string using a set of predefined rules. It is our job to decode the strings properly and get the information we want.

The json_decode() function accepts four parameters but you will only need the first two in most situations. The first parameter specifies the string that you want to decode. The second parameter determines how the decoded data is returned back. Setting it to true will return an associative array and false will return objects. Here is a basic example. We have a file called people.json with the following contents:

We can read information from this JSON file by using the code below:

In the above example, json_decode() returned an object because the second parameter was set to false. You can set it to true to get the data back as an associative array.

Now, we will decode JSON that is slightly more complicated and try to get back useful information from it.

Our goal is to get back all the countries visited by the person in different years. The value returned by $decoded_json['countries'] will actually be an array and we will loop through it like regular arrays to get our data.

Lets go over just one last example of extracting information from a JSON file. Here is the JSON from which we will extract our data.

We have two nested arrays in the JSON data this time. So, we will be using two nested loops to get the countries visited by different customers.

You should now have a rough idea of the approach you should take to read JSON data from a file depending on how it has been created.

Reading JSON Data Without Knowing Keys Beforehand

So far we have read JSON data where we already knew all the keys. That might not always be true. Luckily, we can still extract useful information from the file once we have stored it as an associative array. The following example should clear things up.

The keys in the above JSON seem to be random strings that we cannot predict beforehand. However, once we convert it into an associative array we will no longer need to know the exact key values to iterate through the data.

Creating JSON Data in PHP

You can also turn your own data into a well formatted JSON string in PHP with the help of the function json_encode(). It basically accepts three parameters but you will usually only need the first one i.e., the value you want to encode in most situations.

You might also need to use some flags in order to get the JSON string in desired format. For example, the JSON_PRETTY_PRINT flag can be used to add white space for proper formatting of JSON string. Similarly, you can use the JSON_PRESERVE_ZERO_FRACTION flag to make sure float values are always stored as floats even if they are equivalent to some integer in magnitude. You can see a list of all such flags in the official documentation.

Dealing with Errors During Encoding and Decoding

The JSON format requires us to follow a specific set of rules for proper encoding and decoding of the strings. For example, names and values should be enclosed in double quotes and there should be no trailing comma after name-value pairs. The json_last_error_msg() function can help you figure out what kind of error you are getting so that you can take appropriate steps. Here is a very basic example:

Final Thoughts

In this tutorial, you learned how to read JSON data from a file or string in PHP. We also learned how to convert that JSON into an array and traverse it to extract the information we want. You should now be able to get information from JSON in a file where you don’t know all the keys in key-value pairs. In the last two sections, we covered how you can stringify data as JSON in PHP and the errors you might encounter during the encoding and decoding process.

Hopefully, this will answer all your questions about encoding and decoding JSON in PHP.


Comments 0
There are currently no comments.