PHP JSON Encode and Decode

This article is going to deal with set of PHP operations that are used to encode given data into JSON data structure and to decode JSON data into its original form. We have seen url_encode() and url_decode() to perform same set of these encoding and decoding operations with respect to given URL

Similarly, PHP provides couple of functions to perform JSON encode and decode. These functions are,

  1. json_encode()
  2. json_decode()

In this article we are going to learn more about these functions.

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.

php_json_encode_decode

Predefined JSON Constants

For PHP JSON encode, the following list of constants will be used for the options parameter of 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 object for given input data except associative array.
  • JSON_NUMERIC_CHECK – PHP JSON encode function will return numbers as a result of encoding given number with string data type.
  • JSON_BIGINT_AS_STRING – This constant is used to convert the log integer value as string.
  • JSON_PRETTY_PRINT – pretty print is used for adding white space with the JSON formatted data.
  • JSON_UNESCAPED_SLASHES – It prevents from escaping slashes (/).
  • JSON_UNESCAPED_UNICODE – It prevents from escaping unicode characters.
  • Example: PHP json_encode()

    Now, its time to see an example PHP program to perform JSON encode. So, the following program handles few json_encode() function invoke with some of the available JSON encode constants as its option 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 covert 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 with an index even though if input array doesn’t have any 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.
    • Boolean value set based on which an associative array will be returned, if it is true.
    • depth limit.
    • options.

    The third and fourth arguments are same as we have seen for json_encode(). Default value for depth limit is 512. And, the PHP supported constant for 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.

    ...
    $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, te 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 associative array or object with key and value pair for json_decode(), the key value should be enclosed within double quotes. Otherwise, json_decode() will return NULL.

    Download PHP JSON Encode Decode Source Code

    This PHP code tutorial was published on August 17, 2013.

    ↑ Back to Top