
JSON stand for JavaScript Object Notation. It is a lightweight data-interchange format. It is easy for humans to read and write and also easy for machines to parse and generate. JSON is used to transmit information between a server and a browser. This is text, that can be convert to any JavaScript object into JSON and send JSON to the server. We can also convert any received JSON from the server into JavaScript objects. In this blog, we explain you how to encode and decode JSON using PHP.
As PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.
JSON Functions
- json_encode
- json_decode
- json_last_error
PHP json_encode()
PHP json_encode() function is used for encoding JSON in PHP and returns the JSON representation of a value on success or FALSE on failure.
json_encode() has the following basic syntax:
string json_encode ( $value [, $options = 0 ] )
where;
value: It is the value being encoded.
options: This option value is a 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.
Example

After execution, produce the following output:
{“a”:2,”b”:5,”c”:6,”d”:8,”e”:7}
PHP json_decode()
This function is used for decoding JSON in PHP and returns the value decoded from json to appropriate PHP type.
json_decode() has the following basic syntax:
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
where;
json_string : It is an encoded string which must be UTF-8 encoded data.
assoc : It is a boolean type parameter that convert returned objects into associative arrays when set to TRUE.
depth : It’s an integer type parameter which specifies the recursion depth.
options : This is an integer type bitmask of JSON decode, JSON_BIGINT_AS_STRING is supported.
Example

After execution, produce the following output:
array(5) {
[“a”] => int(1)
[“b”] => int(2)
[“c”] => int(3)
[“d”] => int(4)
[“e”] => int(5)
}
PHP json_last_error()
json_last_error function is used to returns the last error occurred.
json_last_error() has the following basic syntax:
int json_last_error ( void )
This function has no parameters.