php json_decode解析失败的解决办法:1、通过json_last_error等函数获取错误码;2、根据utf8的编码范围剔除掉非法utf8字符。
本文操作环境:windows7系统、php7.1版,dell g3电脑
php json_decode 解析失败怎么办?
php json_decode解析失败及错误处理
一般情况下,获取到一段json内容,直接json_decode($content, true)就转成array来用了,很方便。
但是,如果给你提供json内容的接口出了点问题,给的json不标准或是干脆有错误,那就要想办法来找出问题了。
先看看json_encode的manul
https://www.php.net/manual/en/function.json-last-error.php
失败时返回null
// $json = '{a:1,b:2,c:3,d:4,e:5, name:corwien}'; $json = '{a:1,b:2,c:3,d:4,e:5, name:}'; //错误的json格式 $result = json_decode($json, true); if(!$result) { //error handle ,错误处理 $ret = json_last_error(); print_r($ret); //打印为: 4,查错误信息表,可知是语法错误 } json_last_error错误msg对照表:0 = json_error_none1 = json_error_depth2 = json_error_state_mismatch3 = json_error_ctrl_char4 = json_error_syntax5 = json_error_utf8
我们如何知道错在哪里了呢?
1、获取错误码php有一个json_last_error函数,见
https://www.php.net/manual/en/function.json-last-error.php
它会返回错误码告诉我们是什么原因出错了。
错误码看不懂?可以用json_last_error_msg,见
https://www.php.net/manual/en/function.json-last-error-msg.php
不过json_last_error_msg只在php >= 5.5.0版本才有,如果版本低,就自己定义一个吧。
2、低版本php json错误码不全但是,注意看manual就会发现,json_last_error定义的很多错误码都是在高版本里才有的,低版本的php就歇菜了。例如json_error_utf8这个错误码明白地告诉我们json字符串中有非法utf8字符,但是只在php >= 5.3.3中才有。而很悲剧的是,我的php就是5.3.2....
所以,如果你的json_last_error返回的是json_error_none(0) ,并不是说没有错误,而只是这个错误在你的低版本php中没有定义。再说,没有错误怎么会失败呢....
如果是json格式错误,再低版本的php都会告诉你json_error_syntax,所以碰上json_error_none第一个可能性就往非法utf8字符串想.
3、如何处理json中的非法utf8字符根据utf8的编码范围,是可以剔除掉非法utf8字符的。
可以参见https://magp.ie/2011/01/06/remove-non-utf8-characters-from-string-with-php/
//reject overly long 2 byte sequences, as well as characters above u+10000 and replace with ?$some_string = preg_replace('/[\x00-\x08\x10\x0b\x0c\x0e-\x19\x7f]'. '|[\x00-\x7f][\x80-\xbf]+'. '|([\xc0\xc1]|[\xf0-\xff])[\x80-\xbf]*'. '|[\xc2-\xdf]((?![\x80-\xbf])|[\x80-\xbf]{2,})'. '|[\xe0-\xef](([\x80-\xbf](?![\x80-\xbf]))|(?![\x80-\xbf]{2})|[\x80-\xbf]{3,})/s', '?', $some_string ); //reject overly long 3 byte sequences and utf-16 surrogates and replace with ?$some_string = preg_replace('/\xe0[\x80-\x9f][\x80-\xbf]'. '|\xed[\xa0-\xbf][\x80-\xbf]/s','?', $some_string );
这里是把非法字符替换成?,根据需要自己改。
推荐学习:《php视频教程》
以上就是php json_decode 解析失败怎么办的详细内容。