file_get_contents() Breaks Up UTF-8 Characters


I am loading a HTML from an external server. The HTML markup has UTF-8 encoding and contains characters such as ľ,š,č,ť,ž etc. When I load the HTML with file_get_contents() like this:

$html = file_get_contents('');

It messes up the UTF-8 characters and loads Å, ¾, ¤ and similar nonsense instead of proper UTF-8 characters.

How can I solve this?


I tried both saving the HTML to a file and outputting it with UTF-8 encoding. Both doesn't work so it means file_get_contents() is already returning broken HTML.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
<html xmlns="" xml:lang="sk" lang="sk">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Language" content="sk" />



$html = file_get_contents('');
echo htmlentities($html);


11/11/2012 11:25:48 AM

Accepted Answer

Alright. I have found out the file_get_contents() is not causing this problem. There's a different reason which I talk about in another question. Silly me.

See this question: Why Does DOM Change Encoding?

5/23/2017 11:55:10 AM

I had similar problem with polish language

I tried:

$fileEndEnd = mb_convert_encoding($fileEndEnd, 'UTF-8', mb_detect_encoding($fileEndEnd, 'UTF-8', true));

I tried:

$fileEndEnd = utf8_encode ( $fileEndEnd );

I tried:

$fileEndEnd = iconv( "UTF-8", "UTF-8", $fileEndEnd );

And then -

$fileEndEnd = mb_convert_encoding($fileEndEnd, 'HTML-ENTITIES', "UTF-8");

This last worked perfectly !!!!!!

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow