Ric*_*nop 58 php utf-8 file-get-contents
我正在从外部服务器加载HTML.HTML标记具有UTF-8编码,并包含诸如ľ,š,č,ť,ž等字符.当我使用file_get_contents()加载HTML时,如下所示:
$html = file_get_contents('http://example.com/foreign.html');
Run Code Online (Sandbox Code Playgroud)
它弄乱了UTF-8字符并加载Å,¾,¤和类似的废话而不是正确的UTF-8字符.
我怎么解决这个问题?
更新:
我尝试将HTML保存到文件并使用UTF-8编码输出.两者都不起作用,这意味着file_get_contents()已经返回损坏的HTML.
UPDATE2:
<!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>
Run Code Online (Sandbox Code Playgroud)
小智 103
我和波兰语有类似的问题
我试过了:
$fileEndEnd = mb_convert_encoding($fileEndEnd, 'UTF-8', mb_detect_encoding($fileEndEnd, 'UTF-8', true));
Run Code Online (Sandbox Code Playgroud)
我试过了:
$fileEndEnd = utf8_encode ( $fileEndEnd );
Run Code Online (Sandbox Code Playgroud)
我试过了:
$fileEndEnd = iconv( "UTF-8", "UTF-8", $fileEndEnd );
Run Code Online (Sandbox Code Playgroud)
然后 -
$fileEndEnd = mb_convert_encoding($fileEndEnd, 'HTML-ENTITIES', "UTF-8");
Run Code Online (Sandbox Code Playgroud)
这最后工作得很好!!!!!!
Gor*_*don 69
在file_get_contents的PHP手册条目的注释中建议的解决方案
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));
}
Run Code Online (Sandbox Code Playgroud)
您也可以尝试运气http://php.net/manual/en/function.mb-internal-encoding.php
小智 5
我想你只需要在那里进行双重转换:D
可能是因为你在html文档中打开了一个html文档.所以你最终会看到这样的东西
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test</title>.......
Run Code Online (Sandbox Code Playgroud)
mb_detect_encoding因此,使用可能会导致您遇到其他问题.
小智 5
示例:
$string = file_get_contents(".../File.txt");
$string = mb_convert_encoding($string, 'UTF-8', "ISO-8859-1");
echo $string;
Run Code Online (Sandbox Code Playgroud)