Encountered a problem about php7 json_decode null!
Specific problem description:
1. Confirm that the file has no BOM header
2. Tried the following methods to remove illegal strings, but still Output 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() outputs 4, Syntax error, malformed JSON
4. Directly output string, the browser can parse josn normally, as shown in the screenshot below
Solution:
Because your string is not a standard JSON string, each string type of a standard JSON string must be raised with "
test code
<?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));
result
NULL int(4) --------分割线-------- array(2) { ["status"]=> array(2) { ["RetCode"]=> int(0) ["msg"]=> string(7) "success" } ["data"]=> array(0) { } }
============== Update======== ======
After debugging, it was found that it was caused by BOM. The following is the solution
$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);
Recommended study: "PHP7 Tutorial"
The above is the detailed content of Encountered a problem about php7 json_decode null!. For more information, please follow other related articles on the PHP Chinese website!