Rumah > Artikel > pembangunan bahagian belakang > JSON在php中的使用_PHP教程
从5.2版本开始,PHP原生提供json_encode()和json_decode()函数,前者用于编码,后者用于解码。
json_encode()
该函数主要用来将数组和对象,转换为json格式。
<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只接受utf-8编码的字符,json_encode()的参数必须是utf-8编码。
<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>;
输出结果:
当类中的属性为私有变量的时候,则不会输出。
json_decode()
该函数用于将json文本转换为相应的PHP数据结构。
<span>$json</span> = '{"a":"hello","b":"world","c":"zhangsan","d":20,"e":170}'<span>; </span><span>var_dump</span>(json_decode(<span>$json</span>));
输出结果:
通常情况下,json_decode()总是返回一个PHP对象。
转成数组的:
<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));
转载请注明出处:http://www.cnblogs.com/yydcdut/p/3751141.html