file_get_contents() 分解 UTF-8 字符

2021-12-28 00:00:00 utf-8 php file-get-contents

我正在从外部服务器加载 HTML.HTML 标记具有 UTF-8 编码并包含诸如 ľ,š,č,ť,ž 等字符.当我使用 file_get_contents() 加载 HTML 时,如下所示:

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('http://example.com/foreign.html');

它弄乱了 UTF-8 字符并加载了 Å、¾、¤ 和类似的废话,而不是正确的 UTF-8 字符.

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

我该如何解决这个问题?

How can I solve this?

更新:

我尝试将 HTML 保存到文件并使用 UTF-8 编码输出.两者都不起作用,所以这意味着 file_get_contents() 已经返回损坏的 HTML.

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.

更新2:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="sk" lang="sk">
<head>

<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" />
<title>Test</title>

</head>
<body>


<?php

$html = file_get_contents('http://example.com');
echo htmlentities($html);

?>

</body>
</html>

推荐答案

好的.我发现 file_get_contents() 没有导致这个问题.我在另一个问题中谈到了不同的原因.傻我.

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.

看到这个问题:为什么DOM会改变编码?

相关文章