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

时间:2017-08-30 15:21:09

标签: php domdocument

我试图用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的错误?

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:1)

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

相关问题