file_get_contents() Breaks Up UTF-8 Characters

file_get_contents() Breaks Up UTF-8 Characters

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

Stefan Bogdanescu

Founder & Senior Architect

file_get_contents() Breaks Up UTF-8 Characters

When fetching external HTML that contains characters like ľ, š, č, ť, or ž, using file_get_contents() can result in garbled output displaying as ****, ¾, ¤, or similar nonsense. This behavior isn't a quirk of how PHP handles strings internally; it is a direct consequence of the HTTP response encoding and the underlying stream handling logic.

The core issue lies in how PHP processes binary data returned from an HTTP request when the default_socket_timeout or default context settings are involved, but more critically, it often stems from the server sending the content with an incorrect charset declaration versus what the client expects, combined with how PHP decodes the stream.

In your specific case, the target server claims to serve UTF-8 via a <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> tag. However, file_get_contents() retrieves the raw byte stream. If the remote server is not actually sending a proper HTTP header indicating charset=utf-8, or if the bytes are indeed UTF-8 but PHP's internal conversion layer interprets them based on the system default encoding (often ISO-8859-2 for Slovak systems given the lang="sk" attribute), you get mojibake.

The update noting that saving to a file and echoing with UTF-8 output doesn't fix it confirms that the data is already corrupted in memory before your script processes it. This suggests the HTTP response itself might be using an incorrect encoding (e.g., ISO-8859-2) despite the meta tag, or the server failed to set the Content-Type: text/html; charset=utf-8 header correctly at the HTTP level. Browsers are often forgiving of this mismatch by relying on the meta tag, but PHP's stream wrapper is not.

Using mb_internal_encoding and Stream Contexts

To resolve this without changing the remote server, you must ensure PHP treats the incoming bytes as UTF-8 before processing them. The most reliable method involves adjusting the internal encoding or using a custom stream context.

First, ensure your environment is ready to handle multibyte characters:

mb_internal_encoding('UTF-8');

This sets the default character set for string functions like str_replace or htmlentities. However, this alone might not fix the raw HTML fetching if the stream context defaults to a different encoding.

A more robust approach is to use stream_context_create() to explicitly define the behavior of the HTTP request:

$options = [
    'http' => [
        'header' => "Content-Type: text/html; charset=utf-8\r\n",
        'ignore_errors' => true,
    ]
];

$context = stream_context_create($options);

// Fetching raw bytes first
$htmlBytes = file_get_contents('http://example.com/foreign.html', false, $context);

// If the remote server didn't send UTF-8 in headers, we must decode manually based on what they *say* they are sending
// But if the bytes are actually ISO-8859-2 disguised as UTF-8, manual conversion is needed.

If the remote server is genuinely sending UTF-8 bytes but failing to set the HTTP header, and your PHP environment defaults to an incompatible encoding (like ISO-8859-2), you can force a conversion:

$html = file_get_contents('http://example.com/foreign.html');
// If the server claims UTF-8 but we suspect it's actually ISO-8859-2 due to mojibake:
if ($html) {
    // Attempt to detect and convert if necessary, though this is risky without knowing the source truth
    $html = mb_convert_encoding($html, 'UTF-8', 'ISO-8859-2'); 
}

However, guessing the source encoding is brittle. The safest path is to ensure the remote server sends the correct Content-Type header. If you cannot control that server, inspecting the raw response headers via a tool like curl -I or wget --server-response will reveal the actual HTTP Content-Type.

Handling the Response Headers

If the HTML looks garbled immediately after file_get_contents(), it is highly likely the server sent bytes in an encoding that does not match its declared charset. For instance, a Slovak server might default to ISO-8859-2 (Windows-1250) but claim UTF-8.

If you have full control over your own application and need to fetch such content reliably, consider using the cURL extension, which offers more granular control over encoding detection:

$ch = curl_init('http://example.com/foreign.html');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, ''); // Disable automatic compression/encoding handling to get raw bytes
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$html = curl_exec($ch);
curl_close($ch);

// If cURL returns raw bytes and we know the encoding from headers or meta tags, decode explicitly

The Role of LaravelCompany

For projects built on Laravel, handling external resources with mixed encodings can be tricky. While file_get_contents() is a standard PHP function, modern Laravel applications often rely on HTTP clients that handle redirects and header parsing more gracefully. If you are using Laravel's HTTP client, it generally respects the Content-Type header better than raw stream functions, though explicit encoding conversion may still be required if the remote source is non-compliant.

Summary of Recommendations

  1. Verify Remote Headers: Use a tool like curl -I to check if the server actually sends charset=utf-8 in the HTTP response headers.
  2. Don't Rely on Meta Tags Alone: PHP does not automatically read <meta> tags to change its internal stream encoding. It relies on system defaults or explicit context settings.
  3. Force Encoding Conversion: If the server is non-compliant (sending ISO-8859-2 bytes but claiming UTF-8), you must manually convert using mb_convert_encoding after fetching, assuming you know the true source encoding.
  4. Use cURL for Complex Cases: For production code where encoding reliability is critical, switch from file_get_contents() to curl_exec() with explicit header handling.

By understanding that file_get_contents() retrieves raw bytes and does not perform automatic charset sniffing based on HTML meta tags, you can implement the necessary conversion steps to render characters like ľ correctly.

Our network