遇到一个关于php7 json_decode null问题!
具体问题描述:
1、确认文件无BOM头
2、尝试了如下多种方式去除非法字符串,但是仍然输出NULL
$some_string = htmlspecialchars_decode($some_string); $some_string = preg_replace("/t/", " ", $some_string); $some_string = preg_replace("/n/", ' ', $some_string); $some_string = str_replace("n", ' ', $some_string); $some_string = str_replace ('n','', $some_string);
3、json_last_error()输出4,Syntax error, malformed JSON
4、直接输出字符串,浏览器能够正常解析josn,如下截图
解决办法:
因为你的字符串不是标准的JSON字符串, 标准的JSON字符串每个string类型都要用"引起了
测试代码
<?php $jsonStr1 = '{status: {RetCode:0, msg: "success"}, data: {}}'; var_dump(json_decode($jsonStr1, true)); var_dump(json_last_error()); echo "--------分割线--------".PHP_EOL; $jsonStr2 = '{"status": {"RetCode":0, "msg": "success"}, "data": {}}'; var_dump(json_decode($jsonStr2, true));
结果
NULL int(4) --------分割线-------- array(2) { ["status"]=> array(2) { ["RetCode"]=> int(0) ["msg"]=> string(7) "success" } ["data"]=> array(0) { } }
============== 更新 ==============
经过调试,发现是 BOM 引起的,下面是解决方案
$dataString = $merchant_arr['data']; $A = substr($dataString, 0, 1); $B = substr($dataString, 1, 1); $C = substr($dataString, 2, 1); if ((ord($A) == 239) && (ord($B) == 187) && (ord($C) == 191)) { $dataString = substr($dataString, 3); } $dataArray = json_decode($dataString, true);
推荐学习:《PHP7教程》