How to solve JSON_ERROR_UTF8 error in php json_decode?

How to solve JSON_ERROR_UTF8 error in php json_decode?

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

Stefan Bogdanescu

Founder & Senior Architect

The Real Cause of JSON_ERROR_UTF8 in PHP

When you encounter the JSON_ERROR_UTF8 error while parsing a response from an external API, the immediate instinct is often to force a character encoding conversion. In your specific case, wrapping the input with utf8_encode() before decoding is a common misconception that actually prevents the fix.

The function json_decode does not fail because the JSON string lacks UTF-8 characters per se; it fails because the string passed to it is explicitly not valid UTF-8. The error constant JSON_ERROR_UTF8 indicates that one or more characters in the input are invalid according to the UTF-8 standard.

If you look at the response from http://www.google.com/alerts/preview, you will likely find that the source returns data encoded in ISO-8859-1 (Latin-1). This is a legacy encoding standard where every byte represents a character, and the byte value 0x20 is a space, whereas in UTF-8, 0x20 is also a space. However, characters outside the ASCII range differ significantly. For example, a simple "é" in Latin-1 is the single byte 0xE9. In valid UTF-8, that same sequence represents a different character entirely (specifically, U+FFFD REPLACEMENT CHARACTER when interpreted incorrectly).

When PHP's JSON extension attempts to parse this Latin-1 stream as if it were UTF-8, the parser hits invalid byte sequences. The error occurs immediately upon encountering the first non-ASCII character that doesn't conform to UTF-8 encoding rules. Simply calling utf8_encode() on the entire string does not magically fix the data; instead, it creates a new set of invalid bytes based on the original Latin-1 interpretation, which often results in the same error persisting or shifting slightly depending on how the bytes are shifted.

To solve this, you must first inspect the actual encoding of the remote response before attempting to decode it. The most reliable way to determine the encoding is to look at the HTTP headers sent by the server.

$response = file_get_contents("http://www.google.com/alerts/preview?q=test&t=7&f=1&l=0&e", false, stream_context_create([
    'http' => [
        'header' => "Content-Type: application/json\r\n"
    ]
]));

// Check headers to see declared encoding
$headers = get_headers("http://www.google.com/alerts/preview?q=test&t=7&f=1&l=0&e");
foreach ($headers as $header) {
    if (stripos($header, 'Content-Type') !== false) {
        echo "Server Content-Type: $header\n";
    }
}

If the server does not send a Content-Type header specifying charset=utf-8, or if it explicitly sends charset=iso-8859-1, you know you are dealing with Latin-1 data. In many cases, like the Google Alerts example, the server might be sending raw bytes without a proper charset declaration, defaulting to Latin-1 behavior for non-ASCII characters.

Once identified, the solution is straightforward: convert the input string from ISO-8859-1 to UTF-8 before passing it to json_decode. Unlike utf8_encode, which attempts to map single-byte Latin-1 values to multi-byte UTF-8 sequences assuming they are Latin-1, you need to ensure the conversion is explicit.

$jsonRaw = file_get_contents("http://www.google.com/alerts/preview?q=test&t=7&f=1&l=0&e");

// Convert from ISO-8859-1 (Latin-1) to UTF-8
$jsonConverted = iconv('ISO-8859-1', 'UTF-8', $jsonRaw);

if ($decoded = json_decode($jsonConverted, true)) {
    echo "Decoded successfully\n";
} else {
    // Fallback to json_last_error_msg() for debugging
    echo json_last_error_msg(); 
}

Using iconv is generally safer than utf8_encode here because it allows you to specify the source encoding explicitly. If you are unsure of the source encoding, mb_convert_encoding provides a similar safety net:

$jsonConverted = mb_convert_encoding($jsonRaw, 'UTF-8', 'ISO-8859-1');

A critical pitfall to avoid is blindly trusting that utf8_encode works. That function assumes the input is Latin-1 and attempts to map it to UTF-8. If your data happens to contain valid ASCII characters mixed with invalid Latin-1 bytes, utf8_encode might produce a string that looks like UTF-8 but contains surrogate code points or other artifacts that confuse strict parsers later on.

Furthermore, if you are working within the Laravel ecosystem, consider the fact that Laravel's HTTP client (Http::get) handles encoding detection and conversion more robustly than file_get_contents. If you switch to using Laravel's facade:

$response = Http::get('http://www.google.com/alerts/preview?q=test&t=7&f=1&l=0&e');
$jsonRaw = $response->body(); // This might still need conversion depending on headers

However, even with Laravel, you must inspect the underlying bytes if json_decode throws an error. The root issue remains the mismatch between the byte representation of the data and the UTF-8 expectation of the decoder. By explicitly converting the character set prior to decoding, you align the data structure with what PHP expects, resolving the JSON_ERROR_UTF8 exception without needing to inspect every possible depth of the JSON tree.

Our network