这是 PHP 的 DOMDocument 库中的错误吗?

Is this a bug in PHP's DOMDocument Library?

我正在尝试用 PHP 解析一些 HTML,但出现错误。下面是相关代码,可以在命令行中运行($ php script.php).

<?php
function images_to_links($text)
{
    $dom = new \DOMDocument('1.0', 'UTF-8');

    // Load the document, hiding and then restoring error setting
    $internalErrors = libxml_use_internal_errors(true);
    $dom->loadHTML(mb_convert_encoding($text, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    libxml_use_internal_errors($internalErrors);

    // Extract images from the dom
    $xpath = new DOMXPath($dom);

    // Other processing code removed for this example 

    $cleaned_html = $dom->saveHTML();
    return $cleaned_html;
}

$some_text = <<<EOD
<blockquote>asdf</blockquote>
<a href="http://example.com/">click here</a>
<br />
<p><a href="http://example.com/">another link</a></p>
EOD;

print images_to_links($some_text);

预期输出:

<blockquote>asdf</blockquote>
<a href="http://example.com/">click here</a>
<br />
<p><a href="http://example.com/">another link</a></p>

实际输出——注意 blockquote 是如何环绕其他元素的:

<blockquote>asdf<a href="http://example.com/">click here</a><br><p><a href="http://example.com/">another link</a></p></blockquote>

我的代码是否有错误,或者这是 domdocument 的错误?

我不认为这是一个错误。我的假设是,与大多数 DOM 实用程序一样,DOMDocument 期望所有内容都嵌套在单个标签下,例如 <html>.

通过使用 LIBXML_HTML_NOIMPLIED 标志,您告诉 DOMDocument 放弃通常使用部分 HTML 的步骤,方法是将其包装在 <html><body> 标记中。

http://php.net/manual/en/libxml.constants.php

LibXML 需要根节点,因此将它找到的第一个元素解释为根节点(忽略其结束标记)。