Home >Backend Development >PHP Tutorial >Understand the difference between json_encode and json_decode in PHP
##1. json_encode() JSON encodes variables
$book = array('a'=>'xiyouji','b'=>'sanguo','c'=>'shuihu','d'=>'hongloumeng'); $json = json_encode($book); echo $json;The results printed by the browser are as follows:
{"a":"xiyouji","b":"sanguo ","c":"shuihu","d":"hongloumeng"}
##2. json_decode() decodes JSON data and converts it into PHP variables
Syntax: json_decode($json[,$assoc=false[,$depth=512[,$options=0]]])$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);
The results printed by the browser are as follows:
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 seem to be much different, but when the elements inside are called, 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);//调用对象元素
The print result is as follows:
string(6) "sanguo" string(6) "shuihu"This ends the brief analysis of this article This concludes the article on the difference between json_encode and json_decode in PHP. For more information about PHP json_encode and json_decode, please search Script House’s previous articles or continue to browse the relevant articles below. I hope you will support Script House in the future!Related learning recommendations:
PHP programming from entry to proficiency
The above is the detailed content of Understand the difference between json_encode and json_decode in PHP. For more information, please follow other related articles on the PHP Chinese website!