PHP json_decode return error code 4

PHP json_decode return error code 4

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

Stefan Bogdanescu

Founder & Senior Architect

PHP json_decode return error code 4

When json_decode() in PHP returns null and you subsequently check json_last_error(), receiving a value of 4 indicates a specific failure mode: JSON_ERROR_UTF8. This isn't a generic parsing crash; it means the JSON parser successfully recognized the structure but encountered one or more bytes that do not conform to valid UTF-8 encoding.

In many cases, this stems from how data is transmitted over HTTP rather than malicious corruption of the file itself. If you are fetching data from an endpoint like http://pad.skyozora.com/data/pets.json, you might encounter a situation where the raw response contains invisible control characters or malformed byte sequences in non-ASCII ranges (specifically \x00-\x1F and high-bit bytes outside valid UTF-8). A common, albeit risky, workaround involves stripping these bytes using preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $html). While this successfully resolves the parse error by cleaning the string to be valid UTF-8, it introduces a significant side effect: any legitimate characters that fall into those ranges—including Chinese, Japanese, or other high-bit scripts—are also removed.

The root of the issue often lies in the Content-Type header sent by the server. When a server responds with text/html instead of application/json, PHP’s stream wrapper might handle the data differently, or the response body might include hidden BOMs (Byte Order Marks) or other HTML meta-characters mixed into the JSON payload. If you inspect the raw output using a tool like jsonlint.com, you will often see that while the structure appears correct, specific lines terminate with invalid byte sequences immediately following valid characters.

To fix this without data loss, you must first ensure the server sends the correct headers. If you control the server configuration, force the Content-Type header to application/json; charset=utf-8. This signals to PHP that the payload is strictly JSON and helps prevent stream handling issues where extra whitespace or encoding markers are appended.

If you cannot modify the server response, you must clean the data on the client side while preserving valid UTF-8 characters. The regex approach used to strip all high-bit bytes is too blunt an instrument. Instead, you should use a function that attempts to decode the string and ignores invalid byte sequences rather than removing them entirely. However, note that standard PHP json_decode does not have a built-in flag for "ignore invalid UTF-8."

The most robust solution in modern PHP versions (7.4+) involves using mb_convert_encoding or leveraging the fact that json_decode throws a JsonException if strict error handling is enabled. If you are running an older version of PHP, or if the response contains binary junk mixed with text, you might need to use a more sophisticated cleaning function that validates UTF-8 sequences before attempting decoding. For example, you can iterate through the string and rebuild it, skipping only those byte sequences that strictly fail UTF-8 validation rules while leaving valid high-bit characters (like Chinese/Japanese) intact.

Another frequent oversight in debugging this specific error is ignoring the HTTP status code and headers returned by file_get_contents. Even if the content looks like JSON, a response with a status code of 200 but an incorrect Content-Type can lead to parsing ambiguities. Always verify that your request returns a valid JSON payload by checking the header before attempting to decode.

Finally, consider using a dedicated HTTP client library like Guzzle or Laravel's built-in Http facade instead of file_get_contents. These libraries provide better control over headers and allow you to easily inspect the raw response body and headers, making it significantly easier to diagnose whether the issue is local to your decoding logic or systemic within the API response itself. If you are working within a Laravel ecosystem, utilizing the Http facade ensures that you get consistent JSON handling and can easily catch parsing exceptions using try-catch blocks rather than relying on json_last_error().

Our network