JSON stands for JavaScript Object Notation. JSON is an open standard data format used to transfer data quickly and easily. In PHP, there is an in-built function to handle JSON operations like encode and decode.
Objects or arrays can easily be parsed into JSON using those functions. Then we can transfer JSON sting over HTTP/HTTPS and use it as per our requirements. Nowadays, major databases like MYSQL also support JSON data storage and provide query functions for it.
In this tutorial, we will teach you how to read JSON data and convert it to an array in PHP. Learn how to parse JSON using the json_decode() and json_encode() functions.
First of all, let's understand JSON format. JSON stores data just like an array but uses curly brackets to group data and store it into key-value separated by a colon sign. Below is an example of a sample JSON object for user data. We will use this data into further examples.
Below is a sting conversion of above data:
Reading JSON File or String
JSON can be stored in file, database, or even string variable. Here, we will see how to parse JSON file or JSON strings using json_decode() function.
Let's take the first example to read JSON file using json_decode() function in PHP. Here, we have created users.json and stored above data.
Output :
Here, we have parsed JSON into a PHP object and simply print it. The json_decode() function accepts two arguments which are JSON string boolean flag which defines conversion of JSON will be array or object. By default, it converts into an object.
If you want to convert JSON string into an array then pass true as second argument like below example :
It will produce same output as above but here we have converted JSON file into an array and used it.
Creating JSON Data in PHP
The json_encode() function is used to encode a value in JSON format. We can encode associative array, PHP class object, or SQL result object into JSON using json_encode() function.
The json_encode() function accepts three parameters but in general use, just object or array is passed to it. While in the second parameter, we can pass some flag for JSON encoding like JSON_PRETTY_PRINT, JSON_PRESERVE_ZERO_FRACTION, or more. You can overview all flags at Offical PHP Documentation.
Let's take a simple example to convert a color array into JSON.
Output :
Let's take the same example with some flags.
Output :
Conclusion
In this article, you learned how to read JSON data from a file or string in PHP. You also learned how to convert that JSON into an array or object. Also, we have converted an array or object into a JSON string.