json_decode — Decodes a JSON string
Description
mixed json_decode ( string $json [, bool $assoc ] )
Takes a JSON encoded string and converts it into a PHP variable.
Parameters
$json The json string being decoded.
$assoc When TRUE, returned objects will be converted into associative arrays.
Return Values
Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.
Description
mixed json_decode ( string $json [, bool $assoc ] )
Takes a JSON encoded string and converts it into a PHP variable.
Parameters
$json The json string being decoded.
$assoc When TRUE, returned objects will be converted into associative arrays.
Return Values
Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.
php中的json定义较之js更为严谨,遵守json的规范,所以熟练在js中使用并不等于可以在php中运用一样的规则,下面是需要注意的地方:
1、不能使用单引号来引pair,如
print_r(json_decode(’[0,{"a":"a","b":"b"},2,3]’)); //works
print_r(json_decode("[0,{’a':’a',’b':’b'},2,3]")); //doesn’t work
2、和js不一样,不允许末端有多余的逗号
print_r(json_decode(’[0,1 ]’)); //works
print_r(json_decode(’[0,1,]’)); //doesn’t work
3、pair中的键值也必须用双引号引起来
{ bar: “baz” } //js中这样写是可以的
{ “bar": “baz” } //php中必须要用双引号
4、Take care that json_decode() returns UTF8 encoded strings, whereas PHP normally works with iso-8859-1 characters.
$php_vlaues = utf8_decode(json_decode($somedata));
你可以使用json格式验证工具:
http://www.jsonlint.com/
本文介绍了 PHP 中 json_decode 函数的使用方法及注意事项,包括 JSON 字符串的正确格式要求、与 JavaScript 的区别等。

5051

被折叠的 条评论
为什么被折叠?



