At present, JSON has become one of the most popular data exchange formats, and almost all APIs of major websites support it.
In this chapter we will introduce how to use PHP language to encode and decode JSON objects.
Starting from version 5.2, PHP natively provides json_encode() and json_decode() functions, the former is used for encoding, and the latter is used for decoding.
function description
# JSON_ENCODE Pay the variable json encoding
JSON_DECODE to decode the string of json format and convert it to PHP variable
##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.
Syntax
string json_encode ( $value [, $options = 0 ] )
Parameters
value: The value to be encoded. This function is only valid for UTF-8 encoded data.
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_OBJECT
First look at an array conversion Example:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr);
The result is
{"a":1,"b":2,"c":3,"d":4,"e":5}
Let’s look at another example of object conversion:
$obj->body = 'another post'; $obj->id = 21; $obj->approved = true; $obj->favorite_count = 1; $obj->status = NULL; echo json_encode($obj);
The result is
{ "body":"another post", "id":21, "approved":true, "favorite_count":1, "status":null }
PHP json_decode() function is used to decode JSON format strings and convert them into PHP variables.
Syntax
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
Parameters
json_string: The 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: Integer type parameter, which specifies the recursion depth
options: Binary mask, currently only JSON_BIGINT_AS_STRING is supported.
Example
The following example demonstrates how to decode JSON data:
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) }