php

PHP Json_Decode() Function

PHP has two built-in functions to work with the JSON data. These are json_encode() and json_decode() functions. The json_encode() function is used to encode the JSON data and the json_decode() function is used to decode the encoded JSON data. This function creates a PHP object from a JSON object. The different uses of the json_decode() function are shown in this tutorial.

Syntax:
mixed json_decode(string $json, bool $associative=null, int $depth=512, int $flags=0)

This function has four arguments. The first argument is mandatory and the other arguments are optional. The purposes of these arguments are described in the following:

  • $json: It contains the JSON data that is decoded and it only supports the UTF-8 encoded string.
  • $associstive: It contains a Boolean value. If the value of this argument is set to True, the function returns an associative array of the JSON object. If the value of this argument is set to False, the function returns an object.
  • $depth: It is used to define the nested depth of the structure that is decoded. The value of this argument is between 1 to 2147483647.
  • $flag: It contains the bitmask of JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR.

The encoded JSON value of the PHP type is returned by this function if the encoded data is within the nested depth. Otherwise, the function returns NULL.

Different Examples of Json_Encode() Function

The different uses of the json_encode() function are shown in this part of the tutorial using multiple examples.

Example 1: Convert Simple JSON Data Into a PHP Array

Create a PHP file with the following script that converts the JSON object into a PHP object and a PHP array using the json_decode0 function. When the json_decode() function is used with one argument, the JSON object is converted into a PHP object. When the json_decode() function is used with the first two arguments, the JSON object is converted into a PHP array. A JSON object with simple JSON data of five properties is used in this example.

<?php

//Declare a simple JSON string
$jsondata = '{"01":"Book", "02":"Pen", "03":"Pencil", "04":"Rular", "05":"Paper"}';

//Decode the JSON data into a PHP object
echo "<b>The decoded json data as object:</b><br/>";
print_r(json_decode($jsondata));

//Decode the json data into a PHP array
echo "<br/><b>The decoded json data as associative array:</b><br/>";
print_r(json_decode($jsondata, true));

?>

Output:

The following output appears after executing the previous script:

Example 2: Print the JSON Property Names and Values

Create a PHP file with the following script that converts the JSON object into a PHP array using the json_decode0 function. A JSON object with simple JSON data of five properties is used in this example. Next, the “foreach” loop is used to read and print the keys and values of the PHP array.

<?php
 
//Declare a simple JSON string
$productTypes = '{"t01":"HDD", "t02":"Monitor", "t03":"Mouse", "t04":"Printer", "t05":"Keyboard"}';

//Decode the JSON data into a PHP array
$phparray = json_decode($productTypes, true);

echo "<b> ID     Product Name </b><br/>";
//Print the elements of the associative array using the loop
foreach($phparray as $index => $value)
{
    echo $index."    ".$value."<br/>";
}

?>

Output:

The following output appears after executing the previous script:

Example 3: Search the Particular JSON Property

Create a PHP file with the following script that converts the JSON object into a PHP array and the particular ID value will be searched in the array. If the value exists in the array, the corresponding other values are printed. Here, the search ID value is taken from the URL parameter.

<?php

 //Declare a JSON object of more than one depth
 $customerData = '[
   {"ID": "056345", "name":"Mira Hossain", "email":"[email protected]", "contact_no":"+8801954532367"},
   {"ID": "056335", "name":"Mohammed Abir", "email":"[email protected]", "contact_no":"+8801858722209"},
   {"ID": "056387", "name":"Alif Chowdhury", "email":"[email protected]", "contact_no":"+8801700785321"},
   {"ID": "056391", "name":"Nipa Roy", "email":"[email protected]", "contact_no":"+880180006342"},
   {"ID": "056395", "name":"Anam Ali", "email":"[email protected]", "contact_no":"+880159126543"}
]'
;
 
//Create the PHP array of the JSON data
$custArray = json_decode($customerData, true);
//Check the search ID is given in the URL or not
if (isset($_GET['src']))
{
   //Read the search ID from the URL
   $searchID = $_GET['src'];
   $found = false;

   //Print the customer information of the particular ID if exists in the array
   for ($index=0; $index < count($custArray); $index++) {
      if($custArray[$index]["ID"] == $searchID) {
          echo "<b> Customer's details: </b><br/>";
          echo "Name: ".$custArray[$index]["name"]."<br/>";
          echo "Email: ".$custArray[$index]["email"]."<br/>";
          echo "Contact No: ".$custArray[$index]["contact_no"]."<br/>";
          $found = true;
          break;
      }
   }
   if ($found == false)
       echo "Customer ID does not exist.";
}
else
   echo "Search ID is not given."
?>

Output:

The following output appears after executing the previous script if no ID value is provided in the URL:

The following output appears after executing the previous script if the ID value that is provided in the URL exists in the PHP array that is generated from the JSON object:

The following output appears after executing the previous script if the ID value that is provided in the URL does not exist in the PHP array that is generated from the JSON object:

Example 4: Generate Error for the Wrong JSON Object

Create a PHP file with the following script that displays an error at the time of converting the JSON object to a PHP object if the JSON object contains any error. The JSON object that is used in this example contains an error in the value of the second property. The double quotation(“) is missing for the property value, “Pen”.

<?php
//Declare a simple JSON string
$jsondata = '{"01":"Book", "02":Pen", "03":"Pencil", "04":"Rular", "05":"Paper"}';
 
//Decode the json data into a PHP object
echo "<b>The decoded json data as object:</b><br/>";
print_r(json_decode($jsondata));

//Print the error no and error message if exist
echo "Error No: <b>".json_last_error()."</b> <br/>"."Error Message: <b>".json_last_error_msg()."</b>";
?>

?>

Output:

The following output appears after executing the previous script:

Conclusion

The different ways of parsing the JSON data using the json_decode() function are explained in this tutorial using simple examples. We hope that the purpose of using the json_decode() function is cleared for the PHP users after reading this tutorial.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.