php dom 输出错误

wrong output with php dom

我有一个像这样的简单丰富的 utf-8 文本:

$content = '<p> a simple <a href="http://unicode.com"> UTF-8</a> text.
                  <img src ="http://unicode.com/pic.jpeg" /></p>'

所以我想用 php dom:

更改 src 值
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
$imgs = $doc->getElementsByTagName('img');
 $newsrc = 'http://unicode.com/pic.png';
foreach ($imgs as $img) 
{
     $img->setAttribute('src', $newsrc);
}
$content = $doc->saveHTML();
echo $content;

我除了这个输出结果:

<p> a simple <a href="http://unicode.com"> UTF-8</a> text.
                  <img src ="http://unicode.com/pic.png" /> </p>

但我得到这样的结果:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd"> 
<html><body>6;&#1585<p><a href="http://unicode.com">&#1608;&#1740; &#1662;&#1575;&#1585;&#1587;: </a>
&#1662;&#1575;&#1740;&#1711;&#1575;&#1607;
<img src="http://unicode.com/pic.png" /></p></body></html>

现在我不需要任何额外的标签,例如 DOCTYPE、html、body、... 我想要普通的 char 而不是 &#1711;就这样。

我该如何解决?

这在 PHP 5.4+ 中是可能的。只需将 LIBXML_HTML_NODEFDTD and LIBXML_HTML_NOIMPLIED 标志传递给 DOMDocument::loadHTML:

$doc->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);

如果 PHP 5.4+ 不适合您,请参阅 DOMDocument::saveHTML comments 了解替代解决方案。