Home > Article > Backend Development > What are the common methods of php json
php Common json methods: 1. json_encode(), used to decode strings in JSON format; 2. json_encode(), used to decode strings in JSON format; 3. json_last_error() , used to return the last error that occurred.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php json common methods :
1. json_encode()
PHP json_encode() is used to JSON encode variables. This function returns JSON data if executed successfully. , otherwise return FALSE.
Syntax
string json_encode ( $value [, $options = 0 ] )
Example:
<?php $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($arr); ?>
Output result:
{"a":1,"b":2,"c":3,"d":4,"e":5}
2, json_encode()
json_decode() function is used to decode JSON format strings and convert them into PHP variables.
Syntax:
mixed json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
Parameters:
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: Integer type parameter, which specifies the recursion depth
options: Binary mask, currently only JSON_BIGINT_AS_STRING is supported.
Example:
Output result:
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) }
3, json_last_error()
json_last_error — Return the last error that occurred
Syntax:
json_last_error()
If any, return the last error that occurred during JSON encoding and decoding. An integer will be returned, and this value will be one of the following constants:
Constant | Meaning | Availability |
---|---|---|
##JSON_ERROR_NONE
| No error occurred||
##JSON_ERROR_DEPTH Maximum stack depth reached |
||
Invalid or abnormal JSON | ||
The control character is wrong, maybe the encoding is wrong | ||
Syntax error | ||
Exceptional UTF-8 characters, perhaps due to incorrect encoding. PHP 5.3.3 |
||
One or more recursive references in the value to be encoded PHP 5.5.0 |
||
One or more NAN |
or INF
values in the value to be encodedPHP 5.5.0
|
##JSON_ERROR_UNSUPPORTED_TYPE |
specified Type, value cannot be encoded. PHP 5.5.0 |
JSON_ERROR_INVALID_PROPERTY_NAME | |
The specified property name cannot be encoded. PHP 7.0.0 |
JSON_ERROR_UTF16 | |
Malformed UTF-16 characters, possibly because The character encoding is incorrect. PHP 7.0.0 |
Example: |
Decoding: {"Organization": "PHP Documentation Team"} - No errors Decoding: {'Organization': 'PHP Documentation Team'} - Syntax error, malformed JSON
Recommended learning: "
PHP Video Tutorial"
The above is the detailed content of What are the common methods of php json. For more information, please follow other related articles on the PHP Chinese website!