PHP的json函数

常用的json函数无非是json_encode和json_decode,  比较有意思的是json_encode这个函数.

1. json_encode

string json_encode ( mixed $value )

参数: 待编码的 value ,除了resource 类型之外,可以为任何数据类型. 该函数只接受UTF-8编码的数据.

返回值: 编码成功返回一个以JSON形式表示的string.

<?php
  $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
  echo json_encode($arr);
// output:
// {"a":1,"b":2,"c":3,"d":4,"e":5}
  ?>

 

2. json_decode

mixed json_decode ( string $json [, bool $assoc ] )

参数: $json: 待解码的json string格式的字符串, $assoc: 为true时, 返回array而非object.

返回值: 返回一个对象或关联数组.

<?php
  $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
  var_dump(json_decode($json));
  var_dump(json_decode($json, true));
/* output:
object(stdClass)#1 (5) {
  ["a"] => int(1)
  ["b"] => int(2)
  ["c"] => int(3)
  ["d"] => int(4)
  ["e"] => int(5)
  }
  array(5) {
  ["a"] => int(1)
  ["b"] => int(2)
  ["c"] => int(3)
  ["d"] => int(4)
  ["e"] => int(5)
  }
*/
  ?>

 

注意: 

json格式的字符串书写格式比较特别, 名称必须是双引号, 单引号会导致json_decode时候返回null.

<?php
$json_str = "{'name':'Eric', 'age':23}";
var_dump(json_decode($json_str));
// output: null

$json_str = '{"name":"Eric", "age":23,}'; 
//$json_str = "{/"name/":/"Eric/", /"age/":23}"; //这样也行
var_dump(json_decode($json_str));
// 正确的写法, 输出正确
?>

 

参考: JSON的标准: 双引号而非单引号  http://blog.csdn.net/eric6/article/details/5841462

 

posted on 2012-06-09 17:40  DavidYanXW  阅读(291)  评论(0)    收藏  举报