JSON Functions
Function | Description |
json_encode( ) | Returns the JSON representation of a value |
json_decode( ) | Decodes a JSON string. |
json_last_error( ) | Returns the last error occurred. |
PHP json_encode( )
In PHP, json_encode( ) function is used to encode JSON into PHP.
In other words we can say that json_encode( ) function convert PHP variables into JSON String.
Syntax
1 | string json_encode(mixed value,[int options=0] |
json_encode( ) Example 1
1 2 3 4 5 6 7 | <?php $array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($array); ?> |
Output
{“a”:1,”b”:2,”c”:3,”d”:4,”e”:5}
{“a”:1,”b”:2,”c”:3,”d”:4,”e”:5}
json_encode( ) Example 2
1 2 3 4 5 6 7 8 | <?php $array = array("Name"=>"Vineet","Profile"=>"Developer","Mobile"=>"9015501897"); echo json_encode($array); ?> |
Output
{“Name”:”Vineet”,”Profile”:”Developer”,”Mobile”:”9015501897″}
{“Name”:”Vineet”,”Profile”:”Developer”,”Mobile”:”9015501897″}
PHP json_decode( )
In PHP json_decode( ) function is used to decode JSON into PHP.
In other words we can say that json_decode( ) function convert JSON string into PHP variables.
Syntax
1 | mixed json_decode(string json,[bool assoc = false,[int depth=512]] |
json_decode( ) Example 1
1 2 3 4 5 6 7 8 9 | <?php $json1 = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json1)); var_dump(json_decode($json1, true)); ?> |
Output
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)
}
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_decode( ) Example 2
1 2 3 4 5 6 7 | <?php $json2 = '{"Name":"Vineet","Profile":"Developer","Mobile":"9015501897"}'; var_dump(json_decode($json2, true)); ?> |
Output
array(3)
{
[“Name”]=> string(6) “Vineet”
[“Profile”]=> string(9) “Developer”
[“Mobile”]=> string(10) “9015501897”
}
array(3)
{
[“Name”]=> string(6) “Vineet”
[“Profile”]=> string(9) “Developer”
[“Mobile”]=> string(10) “9015501897”
}