Encode Decode JSON In PHP

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 values separated by a colon sign. Below is an example of a sample JSON object for user data. We will use this data in further examples.

[
   {
      "name":"James",
      "email":"james@yahoo.in",
      "phone":"1111111111"
   },
   {
      "name":"Robert",
      "email":"robert@gmail.com",
      "phone":"2222222222"
   },
   {
      "name":"John",
      "email":"john@gmail.com",
      "phone":"3333333333"
   },
   {
      "name":"Patricia",
      "email":"patricia@hotmail.com",
      "phone":"4444444444"
   },
   {
      "name":"Jennifer",
      "email":"jennifer@gmail.com",
      "phone":"5555555555"
   }
]

Below is a sting conversion of the above data:

"[{\"name\":\"James\",\"email\":\"james@yahoo.in\",\"phone\":\"1111111111\"},{\"name\":\"Robert\",\"email\":\"robert@gmail.com\",\"phone\":\"2222222222\"},{\"name\":\"John\",\"email\":\"john@gmail.com\",\"phone\":\"3333333333\"},{\"name\":\"Patricia\",\"email\":\"patricia@hotmail.com\",\"phone\":\"4444444444\"},{\"name\":\"Jennifer\",\"email\":\"jennifer@gmail.com\",\"phone\":\"5555555555\"}]"

Reading JSON File or String

JSON can be stored in a file, database, or even string variable. Here, we will see how to parse JSON file or JSON strings using the json_decode() function.

Let’s take the first example of reading a JSON file using the json_decode() function in PHP. Here, we have created users.json and stored the above data.

<?php

    $userJsonString = file_get_contents('users.json');

    $users = json_decode($userJsonString, false);

    foreach($users as $user){
        echo 'Name: '.$user->name.'</br>email: '.$user->email.'</br>phone: '.$user->phone.'</br>';
    }
?>

Output :

Name: James
email: james@yahoo.in
phone: 1111111111
Name: Robert
email: robert@gmail.com
phone: 2222222222
Name: John
email: john@gmail.com
phone: 3333333333
Name: Patricia
email: patricia@hotmail.com
phone: 4444444444
Name: Jennifer
email: jennifer@gmail.com
phone: 5555555555

Here, we have parsed JSON into a PHP object and simply printed 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 the JSON string into an array then pass true as a second argument like the below example :

<?php

    $userJsonString = file_get_contents('users.json');

    $users = json_decode($userJsonString, true);

    foreach($users as $user){
        echo 'Name: '.$user['name'].'</br>email: '.$user['email'].'</br>phone: '.$user['phone'].'</br>';
    }
?>

It will produce same output as above but here we have converted the 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 arrays, PHP class objects, or SQL result objects into JSON using the json_encode() function.

The json_encode() function accepts three parameters but in general use, just an object or array is passed to it. While in the second parameter, we can pass some flags 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.

<?php
    $colors = array("Red", "Blue", 'Black', 'Yellow');

    echo json_encode($colors);
?>

Output :

["Red","Blue","Black","Yellow"]

Let’s take the same example with some flags.

<?php
    $colors = array("Red", "Blue", 'Black', 'Yellow');

    echo json_encode($colors, JSON_PRETTY_PRINT|JSON_PRESERVE_ZERO_FRACTION);
?>

Output :

[
    "Red",
    "Blue",
    "Black",
    "Yellow"
]

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.