Home > Article > Backend Development > Use of JSON in php_PHP tutorial
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.
json_encode() This function is mainly used to convert arrays and objects into json format.
Output result:
<span>$arr</span> = <span>array</span> ('a'=>'a','b'=>'b','c'='c','d'=>'d','e'='e'<span>); </span><span>echo</span> json_encode(<span>$arr</span>);
json only accepts utf-8 encoded characters, and the parameters of json_encode() must be utf-8 encoded.
Output result:
<span>class</span><span> person { </span><span>public</span> <span>$name</span><span>; </span><span>public</span> <span>$age</span><span>; </span><span>public</span> <span>$height</span><span>; </span><span>function</span> __construct(<span>$name</span>,<span>$age</span>,<span>$height</span><span>) { </span><span>$this</span>->name = <span>$name</span><span>; </span><span>$this</span>->age = <span>$age</span><span>; </span><span>$this</span>->height = <span>$height</span><span>; } } </span><span>$obj</span> = <span>new</span> person("zhangsan",20,100<span>); </span><span>$foo_json</span> = json_encode(<span>$obj</span><span>); </span><span>echo</span> <span>$foo_json</span>;
When the attributes in the class are private variables, they will not be output.
json_decode()
This function is used to convert json text into the corresponding PHP data structure. Output result:
Normally, json_decode() always returns a PHP object.
<span>$json</span> = '{"a":"hello","b":"world","c":"zhangsan","d":20,"e":170}'<span>; </span><span>var_dump</span>(json_decode(<span>$json</span>));
converted into array:
<span>$json</span> = '{"a":"hello","b":"world","c":"zhangsan","d":20,"e":170}'<span>; </span><span>var_dump</span>(json_decode(<span>$json</span>,ture));
Please indicate the source for reprinting: http://www.cnblogs.com/yydcdut/p/3751141.html
http://www.bkjia.com/PHPjc/776511.htmlwww.bkjia.com
true