如何使用php获取utf8编码文件


how to get utf 8 encoded file with php

我想用PHP从文件夹中获取一个.html.txt文件,但这个文件是UTF-8编码的,如果我使用$html=file_get_contents('somewhere/somewhat.html');,然后使用echo $html;,那么它就不会是UTF-8编码。我看到很多"�"。有什么想法吗?我该如何防止这种情况发生?

您需要自己将其转换为UTF8。为此,请使用mb_convert_encoding()和mb_detect_encodiing()PHP函数。

像这样,

$html=file_get_contents('somewhere/somewhat.html');
$html=mb_convert_encoding($html, 'UTF-8',mb_detect_encoding($html, 'UTF-8, ISO-8859-1', true));
echo $html;

mb_convert_encoding()转换字符编码
mb_detect_encoding()检测字符编码

尝试在字符串上使用iconv:http://php.net/manual/pl/function.iconv.php

其他解决方案:http://php.net/manual/en/function.mb-convert-encoding.php

或者:http://php.net/manual/en/function.utf8-encode.php