json_decode encodes JSON-formatted strings, while json_encode JSON-encodes variables. The following article will introduce to you how to use json_decode() and json_encode(). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
1. json_encode() JSON encoding of variables
Syntax:
json_encode ( $value [, $options = 0 ] )
Note:
1. $value is the value to be encoded, and this function is only valid for UTF8 encoded data;
2. options: a 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;
3. The second parameter is generally not needed;
4. The json data is actually a string, and you can use var_dump() to print it out and view the data. Type;
5. JSON data is returned if the execution is successful, otherwise FALSE is returned.
eg:
//执行代码 $book = array('a'=>'lzichun','b'=>'nihao','c'=>'wohenhao','d'=>'ljlong'); $json = json_encode($book); echo $json; //打印出的结果 {"a":"lzichun","b":"nihao","c":"wohenhao","d":"ljlong"}
2. json_decode() decodes JSON data and converts it into PHP variables
Syntax:
json_decode (json[,json [,json[,assoc = false [, $depth = 512 [, $options =0 ]]])
Note:
1. $json is the data to be decoded, which must be utf8-encoded data;
2. $assoc returns an array when the value is TRUE, and an object when FALSE;
3, $ depth is the recursion depth;
4, $option binary mask, currently only supports JSON_BIGINT_AS_STRING;
5, generally only use the first two parameters, if you want data Type data needs to add a parameter true.
eg:
//执行代码 $book = array('a'=>'xiyouji','b'=>'sanguo','c'=>'shuihu','d'=>'hongloumeng'); $json = json_encode($book); $array = json_decode($json,TRUE); $obj = json_decode($json); var_dump($array); var_dump($obj); //打印出的结果 array(4) { ["a"]=> string(7) "xiyouji" ["b"]=> string(6) "sanguo" ["c"]=> string(6) "shuihu" ["d"]=> string(11) "hongloumeng" } object(stdClass)#2 (4) { ["a"]=> string(7) "xiyouji" ["b"]=> string(6) "sanguo" ["c"]=> string(6) "shuihu" ["d"]=> string(11) "hongloumeng" }
The two results don’t look much different, but when calling the elements inside, the methods of array and obj are different.
//执行代码 $book = array('a'=>'xiyouji','b'=>'sanguo','c'=>'shuihu','d'=>'hongloumeng'); $json = json_encode($book); $array = json_decode($json,TRUE); $obj = json_decode($json); var_dump($array['b']);//调用数组元素 echo '<br/>'; var_dump($obj->c);//调用对象元素 //打印出的结果 string(6) "sanguo" string(6) "shuihu"
This article is reproduced from: https://blog.csdn.net/longgeaisisi/article/details/84665523
Recommended learning: PHP Video tutorial
The above is the detailed content of How to use json_decode() and json_encode() in php?. For more information, please follow other related articles on the PHP Chinese website!