网站制作学习网PHP→正文:php中的json
字体:

php中的json

PHP 2010/10/12 14:23:40  点击:不统计

学习www.网for站asp制.cn作

php5.2.0以上的版本都支持了json.主要有两个函数一个是json_encode,一个是json_decode.在前面文章中有有关json的介绍:http://www.forasp.cn/html/1941.html.如果不明白可以学习一下.

json_encode($str),对变量进行JSON编码,也就是说运行后返回结果是json格式的字符串.$str是php的数组,对象等.
例子:
<?php
$a = array("3"=>1,"w"=>2,"dian"=>3,"forasp"=>4,"."=>5,"cn"=>6);
echo json_encode($a);
?>
输出结果:{"3":1,"w":2,"dian":3,"forasp":4,".":5,"cn":6}也就是将上面的数组换成了标准的json格式.

json_decode($str[,flag]) 接受一个 JSON 格式的字符串并且把它转换为PHP变量,参数中$str是标准的json数据格式,flag可选,如果是true则返回的数组,如果不写,返回的是对象
<?php
$a = '{"3":1,"w":2,"dian":3,"forasp":4,".":5,"cn":6}';
var_dump(json_decode($a));
var_dump(json_decode($a,true));
?>
第一个是:object(stdClass)#1 (6) { ["3"]=> int(1) ["w"]=> int(2) ["dian"]=> int(3) ["forasp"]=> int(4) ["."]=> int(5) ["cn"]=> int(6) }
第二个是:{ ["3"]=> int(1) ["w"]=> int(2) ["dian"]=> int(3) ["forasp"]=> int(4) ["."]=> int(5) ["cn"]=> int(6) }

php与json的相关内容就完毕了


·上一篇:php读取xml2 >>    ·下一篇:php模拟提交之fsockopen >>
推荐文章
最新文章