Home >Backend Development >PHP Tutorial >How to Resolve \'SYNTAX ERROR\' in JSON_DECODE() Despit Valid JSON Format?
JSON_ERROR_SYNTAX Despite Valid JSON on Online Formatters
Encountering a "SYNTAX ERROR" response from json_decode() while the JSON appears valid on external formatters can be puzzling. Here's a comprehensive solution:
Hidden Characters Removal:
Invisible characters can cause syntax errors. Remove these characters using the following code:
<code class="php">$json = file_get_contents('http://www.mywebservice'); // Remove unwanted characters for ($i = 0; $i <= 31; ++$i) { $json = str_replace(chr($i), "", $json); } $json = str_replace(chr(127), "", $json); // Handle BOM (Byte Order Mark) if (0 === strpos(bin2hex($json), 'efbbbf')) { $json = substr($json, 3); }</code>
Decoding the Cleaned JSON:
Now that the hidden characters are removed, decode the JSON:
<code class="php">$obj = json_decode($json);</code>
Error Handling:
If decoding still fails, check the specific error code using json_last_error():
<code class="php">switch (json_last_error()) { case JSON_ERROR_NONE: echo 'JSON_ERROR_NONE'; break; case JSON_ERROR_DEPTH: echo 'JSON_ERROR_DEPTH'; break; // ... Other error codes default: echo 'Unknown Error'; break; }</code>
By following these steps, you can rectify JSON syntax errors and successfully decode JSON data. PHP 5.5's json_last_error_msg() function provides additional error details, but may not be necessary after resolving hidden characters and decoding issues.
The above is the detailed content of How to Resolve \'SYNTAX ERROR\' in JSON_DECODE() Despit Valid JSON Format?. For more information, please follow other related articles on the PHP Chinese website!