【问题标题】:Is this a bug in PHP's DOMDocument Library?这是 PHP 的 DOMDocument 库中的错误吗?
【发布时间】:2017-08-30 15:21:09
【问题描述】:

我正在尝试使用 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 的错误?

【问题讨论】:

  • 似乎与LIBXML_HTML_NOIMPLIED有关,虽然不知道为什么...
  • 我不会认为这是一个错误。我的假设是 DOMDocument 与大多数 DOM 实用程序一样,希望所有内容都嵌套在单个标签下,例如 &lt;html&gt;
  • 嗯.. 说得通。拉伸第一个标签以包裹所有内容是没有意义的。我会将其预先包装在&lt;div&gt; 中。谢谢。

标签: php domdocument


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我不会认为这是一个错误。我的假设是 DOMDocument 和大多数 DOM 实用程序一样,希望所有内容都嵌套在一个标签下,例如 &lt;html&gt;

    通过使用LIBXML_HTML_NOIMPLIED 标志,您是在告诉 DOMDocument 放弃通常对部分 HTML 采取的步骤,方法是将其包装在 &lt;html&gt;&lt;body&gt; 标记中。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 2023-03-04
      相关资源
      最近更新 更多