As you know, JSON can be used with many programming languages; It is also popularly used with Java, PHP, and Python. 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

Function Uses
json_decode Decodes a JSON string
json_encode Returns the JSON representation of a value
json_last_error Returns 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 ]]])
Parameter Type Description
json_string string JSON string must be UTF-8 encoded data, which is being decoded,
assoc bool When true, the returned objects will be converted into an associative array.
depth integer Specify recursion depth.
options integer bitmask 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 convert 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 ] )
Parameter Type Description
value multiple JSON all string data must be UTF-8 encoded, which is being encoded.
options Integer Bitmask 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"}


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram