2015-06-30 41 views
0

我想從許多HTML文件中讀取並顯示標題(包含在h1標記中)的內容。這些文件都在同一個文件夾中。閱讀和編碼html

這是HTML文件的樣子:

<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'> 
<html> 
<head> 
    <title>A title</title> 
    <style type='text/css'> 
    ... Styles here ... 
    </style> 
</head> 
<body> 
    <h1>&Ecirc;tre aidant</h1> 
    <p>En g&eacute;n&eacute;ral, les aidants doivent &eacute;quilibrer...</p> 
    ... more tags ... 
</body> 

我試圖用這個PHP腳本來顯示從H1標籤的內容:

<?php 
foreach (glob("test/*.html") as $file) { 
    $file_handle = fopen($file, "r"); 

    $doc = new DOMDocument(); 
    $doc->loadHTMLfile($file); 

    $title = $doc->getElementsByTagName('h1'); 
    if ($title && 0<$title->length) { 
     $title = $title->item(0); 
     $content = $doc->savehtml($title); 
     echo $content; 
    } 
    fclose($file_handle); 
} 
?> 

但輸出包含錯誤的字符。對於示例文件,輸出爲:

Être aidant 

如何實現此輸出?

Être aidant 
+0

文件是否保存爲UTF8?您是否嘗試將字符串轉換爲https://secure.php.net/manual/en/function.fopen.php#104325 – x29a

回答

1

你應該用你的HTML文檔的<head>一個字符集。

<meta charset="utf-8"> 
+0

你的意思是在輸出文件中? – user3218711

+0

是的,對於你所有的'.html'文件,你應該有這個聲明。嘗試一個文件,看看它是否有效。 –

+0

好吧,我在輸出和輸出之前添加了'',我希望幫助! – user3218711

0

你需要使用UTF-8編碼 變化echo $content to echo utf8_encode($content);

+0

感謝您的答案,但輸出成爲'Êtreaidant' – user3218711

+0

如果您刪除utf8_encode比輸出將成爲助理。 您的預期輸出是什麼。 – rocky