json_decode returns JSON_ERROR_SYNTAX but online formatter says the JSON is OK

json_decode returns JSON_ERROR_SYNTAX but online formatter says the JSON is OK

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Debugging JSON_ERROR_SYNTAX When Online Tools Say It's Valid

When your PHP application rejects a JSON payload that online formatters like http://www.freeformatter.com/json-formatter.html validate without issue, the immediate instinct is to assume the validation logic in your environment is broken. However, the error message JSON_ERROR_SYNTAX in this specific context often points not to malformed data, but to a subtle encoding mismatch between what you received and how PHP's parser interprets it.

The core of the problem usually lies in character encoding. JSON is defined as a text format, but strict parsers like json_decode() expect the input to be valid UTF-8. If your web service returns data that looks correct on a browser or an online tool, those platforms often perform their own "smart" rendering or normalization before displaying the result. They might silently convert a BOM (Byte Order Mark) or non-standard characters into something the parser accepts. PHP, conversely, is strict by default. If the incoming stream contains a UTF-8 BOM (the bytes EF BB BF) at the very beginning of the string, json_decode() will fail immediately because it expects the JSON to start with {, [, ", or similar characters, not a BOM sequence.

This is a classic scenario where json_last_error() returns JSON_ERROR_SYNTAX, yet the structure of the JSON itself is perfectly fine. The parser cannot match the expected state machine transitions because the first few bytes are non-compliant control characters.

To resolve this without upgrading to older PHP versions like 5.5 (which introduced json_last_error_msg(), though that function only returns the error name, not a detailed message in modern contexts), you can preprocess the string using mb_convert_encoding or simple byte-level manipulation. Since you cannot easily detect the presence of a BOM programmatically without checking the first three bytes, it is often safer to strip known problematic prefixes if you control the ingestion pipeline.

Here is an approach to handle the potential BOM issue before decoding:

$data = file_get_contents('http://www.mywebservice');

if ($data !== false) {
    // Strip UTF-8 BOM if present
    if (substr($data, 0, 3) === pack('CCC', 0xEF, 0xBB, 0xBF)) {
        $data = substr($data, 3);
    }

    $obj = json_decode($data);

    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            // Success
            break;
        case JSON_ERROR_SYNTAX:
            echo "\r\n\r\n - SYNTAX ERROR \r\n\r\n";
            // At this point, the BOM is likely already stripped, 
            // so check for other issues like trailing commas or unescaped control chars.
            break;
        // ... other cases
    }
}

Another frequent culprit involves invisible Unicode characters that are not standard JSON whitespace. While browsers often render these gracefully, PHP's parser treats them strictly. If the source returns a character like the zero-width space (U+200B) or similar control characters within strings, json_decode will throw a syntax error because these are not valid escape sequences in JSON.

If stripping the BOM doesn't solve the issue, you need to inspect the raw hex dump of the response. Using bin2hex($data) will reveal non-standard bytes that online formatters might be masking. You can then use mb_convert_encoding to explicitly force UTF-8 normalization:

$data = file_get_contents('http://www.mywebservice');
if ($data !== false) {
    // Force conversion to UTF-8 and remove BOM if present during conversion
    $data = mb_convert_encoding($data, 'UTF-8', 'UTF-8'); 
    
    // Alternatively, just ensure strict UTF-8 handling
    $obj = json_decode($data);

    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            break;
        case JSON_ERROR_SYNTAX:
            echo "\r\n\r\n - SYNTAX ERROR \r\n\r\n";
            break;
    }
}

The trade-off here is performance versus robustness. Stripping the BOM adds a small overhead, but it prevents application crashes when dealing with non-compliant APIs. In high-traffic environments, you might consider caching the cleaned data or normalizing the response at the load balancer level if the upstream service consistently sends malformed headers.

If you are working within the Laravel ecosystem, ensure that your configuration does not inadvertently alter the JSON responses before they hit your controller. While Laravel itself handles JSON well, third-party packages or middleware might be modifying the payload. Always verify the raw input when debugging JSON_ERROR_SYNTAX. If the issue persists after these checks, consider reaching out for support at https://laravelcompany.com, as they can offer deeper insights into specific framework behaviors regarding JSON handling.

Our network