牵着老婆满街逛

严以律己,宽以待人. 三思而后行.
GMail/GTalk: yanglinbo#google.com;
MSN/Email: tx7do#yahoo.com.cn;
QQ: 3 0 3 3 9 6 9 2 0 .

php使用json_decode返回NULL

转载自:http://gaoce19871026.blog.163.com/blog/static/11696126201311269172693/

php5.2以后自带json_decode函数,但是对json文本串的格式要求非常严格。

很可能使用该函数得到的返回值是NULL

可以使用使用json_last_error()函数获取到的返回值来帮助我们判断出问题的原因。

其中如果提示错误JSON_ERROR_SYNTAX(Syntax error),表示json串格式错误。

可以通过以下几个方式排错:

1. json字符串必须以双引号包含

$output = str_replace("'", '"', $output);

2. json字符串必须是utf8编码
$output = iconv('gbk', 'utf8', $output);

3.不能有多余的逗号 如:[1,2,]
用正则替换掉,preg_replace('/,\s*([\]}])/m', '$1', $output)


4、不能有换行、制表符:

$jsonstr = '
{"succ":true,"data":{"id":"31","keywords":"","description":"","jianjie":" ","jianjie_short":"bb","nav":"ccc","deleted":"0","url":"http:\/\/travel.sina.com.cn\/beijing\/
"}}';

//$ret=preg_replace("/\t/", " ", $ret);
//$jsonstr = preg_replace("/\n/", ' ', $jsonstr);
$jsonstr = str_replace("\n", ' ', $jsonstr);
//print_r($jsonstr);exit;
//$jsonstr = str_replace ('\n','', $jsonstr);
$jd = json_decode($jsonstr,true);

$errorinfo = json_last_error();
//print_r(JSON_ERROR_DEPTH);
print_r($jd);

//-------------------------------------------------

0 = JSON_ERROR_NONE No error has occurred  

1 = JSON_ERROR_DEPTH   The maximum stack depth has been exceeded  

2 = JSON_ERROR_STATE_MISMATCH   Invalid or malformed JSON  

3 = JSON_ERROR_CTRL_CHAR Control character error, possibly incorrectly encoded  

4 = JSON_ERROR_SYNTAX Syntax error  

5 = JSON_ERROR_UTF8 Malformed UTF-8 characters, possibly incorrectly encoded PHP 5.3.3

posted on 2014-06-09 19:18 杨粼波 阅读(5469) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理