Encoding and Decoding of Json Objects Through PHP

As you know JSON can be used with many programming languages, it is popularly used with Java, PHP, and Python as well. In this tutorial, you will learn about the encoding and decoding of JSON objects through PHP. So, let us dig deep into it.

PHP json_decode and json_encode functions are used to decode and encode JSON object.

PHP JSON Functions

FunctionUses
json_decodeDecodes a JSON string
json_encodeReturns the JSON representation of a value
json_last_errorReturns the last error occurred

json_decode

PHP json_decode() function is used to decode JSON objects, and converts it into a PHP variable.

Syntax:
json_decode ($json [, $assoc = false [, $depth = 512 [, $options = 0 ]]])
ParameterTypeDescription
json_stringstringJSON string must be UTF-8 encoded data, which is being decoded,
assocboolWhen true, the returned objects will be converted into associative array.
depthintegerSpecify recursion depth.
optionsintegerbitmask of JSON decode, JSON_BIGINT_AS_STRING is supported.
Example:
<?php
    $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

    var_dump(json_decode($json));
    var_dump(json_decode($json, true));
?>

This will produce the following results on executing:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

json_encode

PHP json_encode() function is used to covert PHP array/objects into JSON value. this function returns JSON representation of a string if the function success or FALSE on failure.

Syntax:
string json_encode ( $value [, $options = 0 ] )
ParameterTypeDescription
valuemultipleJSON all string data must be UTF-8 encoded, which is being encoded.
optionsIntegerBitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_UNESCAPED_UNICODE.

Example: Converting a PHP array to JSON:

<?php
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
    echo json_encode($arr);
?> 

This will produce the following results on executing:

{"a":1,"b":2,"c":3,"d":4,"e":5}

Example: Converting PHP objects to JSON:

<?php
class Employee {
    public $name = '';
    public $age  = '';
    public $role = '';
}

    $obj = new Employee();
    $obj->name = 'Alex';
    $obj->age  = 24;
    $obj->role = 'PHP Developer';
    
    echo json_encode($obj);
?>

This will produce the following results on executing:

{"name":"Alex","age":24,"role":"PHP Developer"}