Home >Backend Development >PHP Tutorial >PHP uses JSON example analysis_PHP tutorial
Encoding JSON in PHP (json_encode)
PHP json_encode() function is used to encode JSON in PHP. This function returns the value represented by JSON on success, or FALSE on failure.
Grammar:
string json_encode ( $value [, $options = 0 ] ) parameters:
Value: The value to be encoded. This function only applies to UTF-8 encoded data.
Options: This optional value is a bitmask consisting of JSON_HEX_TAG JSON_HEX_QUOT, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT
Example
The following example demonstrates how to convert an array to JSON using PHP:
The code is as follows | |||||
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
When executed, this will produce the following results :
{"a":1,"b" :2,"c":3,"d":4,"e":5} |
代码如下 | |
class Emp { echo json_encode($e); 在执行过程中,这将产生以下结果: {"name":"sachin","hobbies":"sports","birthdate":"08/05/1974 12:20:03 pm"} |
The code is as follows | |
class Emp { echo json_encode($e); When executed, this will produce the following results : {"name":"sachin"," hobbies":"sports","birthdate":"08/05/1974 12:20:03 pm"} |
Decoding JSON in PHP (json_decode)
PHP json_decode() function is used to decode JSON in PHP. This function returns the value decoded from json into the appropriate PHP type.
Grammar:
Mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]]) Parameters:
json_string: It must be a UTF-8 encoded data-encoded string
assoc: This is a boolean type parameter. When set to TRUE, the returned object will be converted into an associative array
Depth: It is an integer type parameter that specifies the recursion depth
Options: It is a bit mask JSON decoding of integer type, supporting JSON_BIGINT_AS_STRING
Example
The following example shows how you can use PHP to decode a JSON object:
The code is as follows | |||||||||||||||||||||||||
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true)); When executed, this will produce the following results : object(stdClass)#1 (5) { array(5) { Suppose the JSON data we obtain is as follows: (can be obtained using curl, fsockopen, etc.)
We can use the following method to get the value we want in PHP language:
Example, combined with database operation
Statement: The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn Previous article:8 essential PHP function development_PHP tutorialNext article:8 essential PHP function development_PHP tutorial Related articlesSee more |