這是我寫的一個函式,用來總結關於使用 loadHTML 和 DOM 函式時,字符集問題(UTF-8...)的先前評論。
它會在 <head> 之後立即添加字符集 meta 標籤,以改進自動編碼偵測,將任何特定字符轉換為 HTML 實體,這樣 PHP DOM 函式/屬性將會回傳正確的值。
<?php
mb_detect_order("ASCII,UTF-8,ISO-8859-1,windows-1252,iso-8859-15");
function loadNprepare($url,$encod='') {
$content = file_get_contents($url);
if (!empty($content)) {
if (empty($encod))
$encod = mb_detect_encoding($content);
$headpos = mb_strpos($content,'<head>');
if (FALSE=== $headpos)
$headpos= mb_strpos($content,'<HEAD>');
if (FALSE!== $headpos) {
$headpos+=6;
$content = mb_substr($content,0,$headpos) . '<meta http-equiv="Content-Type" content="text/html; charset='.$encod.'">' .mb_substr($content,$headpos);
}
$content=mb_convert_encoding($content, 'HTML-ENTITIES', $encod);
}
$dom = new DomDocument;
$res = $dom->loadHTML($content);
if (!$res) return FALSE;
return $dom;
}
?>
注意:它使用 mb_strpos/mb_substr 而不是 mb_ereg_replace,因為在處理巨大的 HTML 頁面時,這似乎更有效率。