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.
Read More:
- [PHP]json_encode Chinese JSON_UNESCAPED_UNICODE returns null in php5.3
- composer Failed to decode response: zlib_decode(): data error
- PHP parse error: syntax error, unexpected ‘use’
- Error during session start; please check your PHP and/or webserver log file and configure your PHP
- [PHP] Array to string conversion error when sending data in post
- PHP: How to parse MHT file into HTML
- PHP use __Sleep() and __wakeup() method serializes the object
- PHP Error Object of class mysqli could not be converted to string in
- PHP php-config is not installed error in ubuntu 16 [How to Solve]
- [Solved] PHP Error: Warning: file_get_contents(): Failed to enable crypto
- Laravel-admin php artisan admin:install error reporting problem solution
- [Solved] TP5 Post receive array error: variable type error: array
- laravel The Process class relies on proc_open, which is not available on your PHP installation.
- PHP: The Difference between \Throwable, \Error and \Exception
- PHP encryption 3DES error Call to undefined function: mcrypt_module_open() solution
- PHP error in Windows: class’ mysqli ‘not found
- Mac: Where is php.ini Location
- How to Solve PHP Error: no package’oniguruma’ found
- [Solved] PHP installation Phalcon expansion error
- How to Hide index.php