php DOMDocument - 操作和编码

Mar*_*ski 2 php domdocument

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($content);
$divs = $dom->getElementsByTagName("div");
foreach ( $divs as $div ) {
    if ( $class = $div->attributes->getNamedItem("class") ) {
        if ( $class->nodeValue == "simplegalleryholder" ) 
            $div->parentNode->removeChild( $div );
    }
}
$content = $dom->saveHTML();
Run Code Online (Sandbox Code Playgroud)

这个简单的代码应该可以帮助我删除

<div class="simplegalleryholder"> .... </div> 
Run Code Online (Sandbox Code Playgroud)

从文件.唯一的问题是,$ content包含utf8编码的特殊字符(ąęść等),它们被进程破坏(我得到的是Å,ż).

我该如何处理这个问题才能得到正确的结果?

goa*_*oat 6

UTF-8在构造函数中指定不会使基础xml处理库将其处理为utf8.以下解决方法真的很糟糕,但它的工作原理相当不错.

$encodingHint = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
$dom->loadHTML($encodingHint . $html);
Run Code Online (Sandbox Code Playgroud)

https://bugs.php.net/bug.php?id=32547

如果您在Web浏览器中查看输出,请发送真实的http标头,而不是http-equiv元标记.这仅供观看.使用domdocument处理特别需要元标记.

header('content-type: text/html; charset=utf-8');
Run Code Online (Sandbox Code Playgroud)