一、json_decode() 对JSON数据进行解码,转换为PHP变量
语法: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);
浏览器打印出的结果如下:
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" }
二、json_encode() 对变量进行JSON编码,
语法: json_encode ( $value [, $options = 0 ] )
- 示例:
$book = array('a'=>'xiyouji','b'=>'sanguo','c'=>'shuihu','d'=>'hongloumeng'); $json = json_encode($book); echo $json;
浏览器打印出的结果如下:
{"a":"xiyouji","b":"sanguo","c":"shuihu","d":"hongloumeng"};