PHP JSON Encode and Decode

by Vincy. Last modified on October 13th, 2022.

JSON encode decode is one of the most frequently required operations. In this article, we are going to see how to encode and decode JSON using PHP. PHP provides built-in functions to perform these two operations. Those are,

  1. json_encode()
  2. json_decode()

In this article, we are going to learn about these functions with suitable examples. Apart from these functions, a complete guide to handling JSON with PHP will be useful for you to know more about PHP JSON.

Encoding and Decoding

Encoding and decoding are the pair of operations which is most importantly used in many application programming. Previously, we have seen PHP functions url_encode() and url_decode() to perform the encoding and decoding of a given URL.

Encoding is used to bundle data with respect to a particular format. This process will be required to preserve data consistency. Decoding is a reverse process that reverts encoded data back to its original form.

PHP JSON Encode

In PHP, json_encode() is used to convert PHP-supported data type into JSON formatted string to be returned as a result of JSON encode operation. This function accepts the following set of arguments.

  • Data to be encoded.
  • Options with JSON encode constants to reflect effects on encoding behavior.
  • Depth limit for performing recursive encoding with nested levels of input.

Predefined JSON Constants

For PHP JSON encodes, the following list of constants will be used for the options parameter of the json_encode() function.

    • JSON_HEX_TAG – Used to encode HTML content by replacing < and > symbol with \u003C and \u003E.
    • JSON_HEX_AMP – Used to encode data by replacing ampersand symbol (&) with \u0026.
    • JSON_HEX_APOS – encode apostrophe (‘) with \u0027.
    • JSON_HEX_QUOT – converts double quotes (“) into \u0022.
    • JSON_FORCE_OBJECT – Using this, json_encode will return an object for given input data except for the associative array.
    • JSON_NUMERIC_CHECK – PHP JSON encode function will return numbers as a result of encoding given a number with the string data type.
    • JSON_BIGINT_AS_STRING – This constant is used to convert the log integer value as a string.
    • JSON_PRETTY_PRINT – pretty print is used for adding white space with the JSON formatted data.
    • JSON_UNESCAPED_SLASHES – It prevents escaping slashes (/).
    • JSON_UNESCAPED_UNICODE – It prevents from escaping Unicode characters.

Example: PHP json_encode()

Now, it’s time to see an example PHP program to perform JSON encoding. So, the following program handles a few json_encode() functions invoked with some of the available JSON encode constants as its options parameter.

<?php
$input_array = array(
    "zero",
    "one",
    "two"
);
// returns ["zero","one","two"]
$str_json_format = json_encode($input_array);
print "JSON Formatted String:" . $str_json_format;
// returns {"0":"zero","1":"one","2":"two"}
$obj_json_format = json_encode($input_array, JSON_FORCE_OBJECT);
print "<br/><br/>JSON Object:" . $obj_json_format;
// returns [ "zero", "one", "two" ]
$strJsonFormat_with_space = json_encode($input_array, JSON_PRETTY_PRINT);
print "<br/><br/>JSON Formatted String with white space:" . $strJsonFormat_with_space;
?>

Note:

      • PHP json_encode() is used to convert any type of data except PHP resource data.
      • While using JSON_FORCE_OBJECT on encoding PHP array value, then each array element will be added to an index even if the input array doesn’t have an index.

Decoding JSON Data using PHP

This is the reverse operation of JSON encode, obviously used to convert JSON encoded data into its original PHP data type from where it is encoded initially.

For that, the second method json_decode() we have listed at the beginning of this article, will be used. This function accepts four arguments as listed below.

      • JSON formatted string to be decoded.
      • The Boolean value set is based on which an associative array will be returned if it is true.
      • depth limit.
      • options.

The third and fourth arguments are the same as we have seen for json_encode(). The default value for the depth limit is 512. And, the PHP supported constantly for the option parameter of this function is, JSON_BIGINT_AS_STRING, which is used to convert long integers into float data.

Example: json_decode()

With the above PHP example program, we need to append the following lines.

<?php
$str_json_array_decoded = json_decode($str_json_format);
print "<br/><br/>Resultant decoded array from JSON array:<br/>";
print "<PRE>";
print_r($str_json_array_decoded);
print "</PRE>";

$str_objJson_decoded = json_decode($obj_json_format);
print "<br/><br/>Resultant decoded object data from JSON object:<br/>";
print "<PRE>";
print_r($str_objJson_decoded);
print "</PRE>";

$str_jsonAry_decoded = json_decode($obj_json_format, true);
print "<br/><br/>Resultant decoded array data from JSON object:<br/>";
print "<PRE>";
print_r($str_jsonAry_decoded);
print "</PRE>";
?>

After that, on executing this code, the following output will be returned to the browser.

Resultant decoded array from JSON array:
Array
(
    [0] => zero
    [1] => one
    [2] => two
)
Resultant decoded object data from JSON object:
stdClass Object
(
    [0] => zero
    [1] => one
    [2] => two
)
Resultant decoded array data from JSON object:
Array
(
    [0] => zero
    [1] => one
    [2] => two
)

Note:

      • While passing an associative array or object with key and value pair for json_decode(), the key value should be enclosed in double-quotes. Otherwise, json_decode() will return NULL.

Download PHP JSON Encode Decode Source Code

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “PHP JSON Encode and Decode”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page