file_get_contents() 分解 UTF-8 字符

2022-08-30 08:37:03

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

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

它搞砸了 UTF-8 字符,并加载了 Å、3/4、¤ 和类似的废话,而不是正确的 UTF-8 字符。

我该如何解决这个问题?

更新:

我尝试将HTML保存到文件并使用UTF-8编码输出它。两者都不起作用,所以这意味着file_get_contents()已经返回了损坏的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>

答案 1

我在波兰语方面也有类似的问题

我试过了:

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

我试过了:

$fileEndEnd = utf8_encode ( $fileEndEnd );

我试过了:

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

然后——

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

最后一次完美地!!!!!!


答案 2

PHP 手册条目注释中建议的解决方案,用于file_get_contents

function file_get_contents_utf8($fn) {
     $content = file_get_contents($fn);
      return mb_convert_encoding($content, 'UTF-8',
          mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
}

您也可以用 http://php.net/manual/en/function.mb-internal-encoding.php 试试运气


推荐