【发布时间】: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 实用程序一样,希望所有内容都嵌套在单个标签下,例如
<html>。 -
嗯.. 说得通。拉伸第一个标签以包裹所有内容是没有意义的。我会将其预先包装在
<div>中。谢谢。
标签: php domdocument