How to Resolve \'SYNTAX ERROR\' in JSON_DECODE() Despit Valid JSON Format?

DDD
Release: 2024-10-22 22:02:29
Original
457 people have browsed it

How to Resolve

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>
Copy after login

Decoding the Cleaned JSON:

Now that the hidden characters are removed, decode the JSON:

<code class="php">$obj = json_decode($json);</code>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!