Object or array can easily parsed into JSON using those functions. Then we can transfer JSON sting over HTTP/HTTPS and use it as per our requirements. Now days, major databases like MYSQL also supports JSON data storage and provide query functions for it.
In this tutorial, we will teach you how to read a 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 array but use curly brackets to group data and stores into key-value separated by colon sign. Below is example of sample JSON object for users data. We will use this data into further examples.
Below is sting conversion of above data:
JSON can be stored into file, database or even string variable. Here, we will see how to parse JSON file or JSON string using json_decode() function.
Let's take first example to read json file using json_decode() function in PHP. Here, we have created users.json and stored above data.
Here, we have parsed json into PHP object and simply print it. The json_decode() function accept two argument first is JSON string and second is boolean flag which define conversion of JSON will be array or object. By default it convert into object.
If you want to convert JSON string into 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 array and use it.
The json_encode() function is used to encode a value to JSON format. We can encode associative array, PHP class object or sql result object into JSON using json_encode() function.
The json_encode() function accept three parameters but in general use just object or array is passed to it. While in second parameter, we can pass some flag for JSON encoding like JSON_PRETTY_PRINT, JSON_PRESERVE_ZERO_FRACTION or more. You can overview all flag at Offical PHP Documentation.
Let's take simple example to convert colors array into JSON.
Let's take same example with some flags.
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 array or object into JSON string.
Ask anything about this examples