In this chapter we will introduce how to use PHP language to encode and decode JSON objects.
JSON extension has been built-in in php5.2.0 and above.
function | describe |
---|---|
json_encode | JSON encode variables |
json_decode | Decode JSON-formatted strings and convert them into PHP variables |
json_last_error | Returns the last error that occurred |
PHP json_encode() is used to JSON encode variables. This function returns JSON data if executed successfully, otherwise it returns FALSE.
string json_encode ( $value [, $options = 0 ] )
value : The value to encode. This function is only valid for UTF-8 encoded data.
options : Binary mask consisting of the following constants: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT
The following example demonstrates how to convert a PHP array to JSON format data:
<?php $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($arr) ;?>
The result of executing the above code is:
{"a":1,"b":2,"c":3,"d":4,"e":5}
The following example demonstrates how to convert PHP objects into JSON format data:
<?php class Emp { public $name = ""; public $hobbies = ""; public $birthdate = ""; } $e = new Emp(); $e->name = "sachin"; $e-> hobbies = "sports"; $e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p"); $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03")); echo json_encode($e);?>
The result of executing the above code is:
{"name":"sachin","hobbies":"sports","birthdate":"08/05/1974 12:20:03 pm"}
The PHP json_decode() function is used to decode JSON-formatted strings and convert them into PHP variables.
mixed json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
json_string : JSON string to be decoded, must be UTF-8 encoded data
assoc : When this parameter is TRUE, an array will be returned, and when FALSE, an object will be returned.
depth : parameter of integer type, which specifies the recursion depth
options : Binary mask, currently only JSON_BIGINT_AS_STRING is supported.
The following example demonstrates how to decode JSON data:
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json)); var_dump (json_decode($json, true));?>
The result of executing the above code is:
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)}