JSON Functions in PHP 5

by   SJRANJAN

jsonJSON (JavaScript Object Notation) is a lightweight data-interchange format. The article explains how to work with JSON in PHP.

json

json_encode()

Generates JSON representation of a value

Syntax:

string json_encode ( mixed $value [, int $options = 0 ] )

Ex:

OutPut:

{“Sachin”:1,”Sourav”:2,”Dravid”:3,”Sehwag”:4,”Virat”:5}

Second attribute is optional … It can be one of the following …

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

By using second attribute we can perform some action while encoding like … , converting quotes into HEX values, converting tags into HEX values, etc …

 

json_decode()

Decodes a JSON string. This function only works with UTF-8 encoded data. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

Syntax:
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

If the second attribute is TRUE , the value returned will be a associative array.

Ex:

OutPut:

object(stdClass)#1 (5) { ["Sachin"]=> int(1) ["Sourav"]=> int(2) ["Dravid"]=> int(3) ["Sehwag"]=> int(4) ["Virat"]=> int(5) }

Last attribute was optional, which gives extra functionalities during decoding process.

 

json_last_error()

Returns the last error occurred during the last JSON encoding/decoding process.

Syntax:
json_last_error()

The function included on PHP 5.3.0 only.

 

Share on :