带有file_get_contents()的UTF8

时间:2014-12-08 18:52:44

标签: php utf-8 file-get-contents

我使用file_get_contents()获取HTML并从网站中删除一些数据。 源并不总是UTF8,但我使用FORCEUTF8类来修复它。但它并没有好好发挥作用。我做错了什么?

/* Load UTF8 HTML */
require_once('/ForceUTF8/Encoding.php');
use \ForceUTF8\Encoding;
function loadHTMLInUtf8($url){
$utf8_or_latin1_or_mixed_string=file_get_contents($url);
return Encoding::toUTF8($utf8_or_latin1_or_mixed_string);
}    

$html=loadHTMLInUtf8('http://www.example.com/');
$dom->loadHTML('<meta http-equiv="content-type" content="text/html; charset=utf-8">'.$html);

有没有其他方法可以做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以使用方法“utf8_encode”。它应该与上面的书面方法相同。

答案 1 :(得分:1)

已知

file_get_contents会破坏UTF8编码。

尝试这样的事情:

<?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));
}
?>

如果这不起作用,请您提供一个示例网址,这不起作用? (我检查了FORCEUTF8库的源代码,这看起来效率不高,我想,这个小函数可以做同样的事情(它在PHP代码中是原生的))。