php json_decode null

----- 网上的--------------

http://webhole.net/2009/08/31/how-to-read-json-data-with-php/    最终解决方案 更新时间 2012年5月31日0:38:42

How To Parse JSON With PHP

------网上找的------------

 

在网上找了很多,都写的例子是json_encode.我把我遇到的这个情况写下吧!

 

【第一种情况】json_decode 之后什么都没有,.  原因之一json_decode只支持utf-8.

iconv('gbk','utf-8', $result_string),用iconv函数改变的编码格式,我个案是gbk..转成utf-8.

 

【第二个情况】  数组对象是需要用print_r ,不能用echo的。

 

【第三个情况】  之后还有乱码情况 ..我的个案是这样的.

header("Content-Type: text/html; charset=UTF-8");

 

php 我也就拿来就用的.没啥基础知识.也没有很多时间.

 

【其他情况】

 在 http://php.net/manual/en/function.json-decode.php (我在网上下载的php manual chm中竟然 没有写这些.真无语... )  中有写到: 

Example #3 common mistakes using json_decode()  一些大家常常常常常常常常常常常常常常犯的错误.. 其他几个例子也可以看看...

<?php

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes    1.这里是说不要使用单引号,正确应该是 $bad_json = '{ "bar": "baz" }';
// single quotes are not valid 
$bad_json "{ 'bar': 'baz' }";
json_decode($bad_json); // null  
 

// the name must be enclosed in double quotes  2.这里是说 名称应该要用""包含起来.. 正确的应该是 $bad_json '{ "bar": "baz" }';就光这个浪费我好几个小时....弄了半天...哎... 
$bad_json '{ bar: "baz" }';
json_decode($bad_json); // null  

// trailing commas are not allowed  3.这里是说 最后一个不需要逗号.
$bad_json '{ bar: "baz", }';
json_decode($bad_json); // null

?>

 

 

如果我们使用 json_encode() 给含有中文的内容进行编码时,会出现类似于\u5c71\u4e1c这样的代码,虽然使用jQuery或者json_decode()进行解码的时候,并不会出现问题,但某些时候,我们还是需要将中文原样的显示出来。

<?php
$code = json_encode($str);
$code = preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))", $code);
?>
posted @ 2012-04-09 22:42  toeasy  阅读(8076)  评论(2编辑  收藏  举报