encode decode json in php

JSON stands for JavaScript Object Notation. JSON is open standard data format which used to transfer data quick and easily. In PHP, there are in-built function to handle JSON operations like encode and decode.

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:

Reading JSON File or String

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.

Output :

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.

Creating JSON Data in PHP

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.

Output :

Let's take same example with some flags.

Output :


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.

Share your thoughts

Ask anything about this examples