Error description
In the PHP development process, when processing json strings, json_decode returns NULL, calling last_error returns 4 (JSON_ERROR_SYNTAX), but json strings can be correctly processed by other languages such as python, javascript or some online json parsers.
Diagnosis
There are several situations that generally cause php json_decode errors here:
1. The json string is read from a file and the character order mark (BOM) is not removed
2. json contains invisible characters, json_decode parsing errors
3. json object value is a single-quoted string
In particular, the third error is relatively hidden, the naked eye is often easy to ignore
Solution:
The following solutions are given for the above three cases
1.BOM Issue:
Open the file in binary mode and confirm whether there is a BOM. If so, remove the BOM before parsing. The following code takes UTF-8 as an example to detect and delete BOM.
function removeBOM($data) {
if (0 === strpos(bin2hex($data), ‘efbbbf’)) {
return substr($data, 3);
}
return $data;
}
2.Invisible character
Remove invisible characters before parsing.
for ($i = 0; $i <= 31; ++$i) {
$s = str_ replace(chr($i), “”, $s);
}
3.Single quote string value
Let’s look at the following example:
<?php
$s = “{\”x\”:’abcde’}”;
$j = json_ decode($s, true);
var_ dump($j);
echo json_ last_ error() . “\n”;
PHP 5.5. 9 output
NULL
four
Generally, you only need to replace single quotation marks with double quotation marks. During specific processing, you should pay attention to that single quotation marks may also appear in other places. Whether to replace them globally needs to be analyzed according to the specific situation.