PHP JSON
In this chapter we will introduce how to use PHP language to encode and decode JSON objects.
Environment configuration
The JSON extension has been built-in in php5.2.0 and above.
JSON Function
Function ##json_encode JSON encoding of variables
json_decode Decodes strings in JSON format and converts them into PHP variables
json_last_error Returns the last error that occurred
1) Parallel data are separated by commas (", ").
2) Mapping is represented by colon (": ").3) The collection (array) of parallel data is represented by square brackets ("[]").
4) The mapped collection (object) is represented by curly brackets ("{}").##json_encode
##PHP json_encode() is used to JSON encode variables. This function returns JSON data if executed successfully, otherwise it returns FALSE. Syntax
string json_encode ( $value [, $options = 0 ] )
Parameters
1. value: the value to encode. This function is only valid for UTF-8 encoded data.
2. options: Binary mask composed 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_OBJECTExample
<?php $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($arr); ?>The execution result of 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 above code execution The result is:
{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}
##json_decode
PHP json_decode() function Used to decode JSON formatted strings and convert them into PHP variables.
Syntax
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
Parameters1. json_string: JSON string to be decoded, must be UTF-8 encoded data2. assoc: When this parameter is TRUE, an array will be returned , returns the object when FALSE.3. depth: parameter of integer type, which specifies the recursion depth
4. options: Binary mask, currently only supports JSON_BIGINT_AS_STRING.
Example
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 execution result of 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)
}