读取和编码html


Reading and encoding html

我正在尝试从许多HTML文件中读取并显示标题的内容(包含在h1标记中)。这些文件都在同一个文件夹中。

这就是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

您应该在HTML文档的<head>中声明一个字符集。

<meta charset="utf-8">

您需要使用utf-8编码更改echo $content to echo utf8_encode($content);