$result = json_decode($string, true);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
json_decode 报错的原因可能不尽相同,但是我遇到的解决方案就是文章顶部推荐的博客那种解决方式
BOM头是UTF-8来告诉编辑器:我是UTF8编码。它的编码是\xEF\xBB\xBF
但是PHP在设计之初并没有考虑到BOM头的问题,所以在编解码的时候很容易出现问题
比如今天遇到的问题,json_decode,当解码的string有BOM头的时候json_decode就解析失败,返回NULL。(为什么不自动检测并去除BOM头呢。。。小吐槽)
$result = trim($result, "\xEF\xBB\xBF");
print_r(json_decode($result, true));
exit;
或者
$result = @iconv("UTF-8", "GBK//IGNORE", $result);
$result = @iconv("GBK", "UTF-8//IGNORE", $result);
print_r(json_decode($result, true));
exit;
网友评论