如何防止DOMDocument将结果包装在 标签中?

问题描述 投票:1回答:1

此主题的点击量达一百万,但似乎没有一个对我有用。所以我不得不再问一次。说,如果我有这个:

$html = "&quot;PHP&quot; is documented <a href=\"https://php.net\">here</a>.";

$dom = new DOMDocument();
$dom->strictErrorChecking = false;
$dom->preserveWhiteSpace = true;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$newHtml = $dom->saveHTML();

echo(htmlentities($newHtml));

为什么得到输出:

<p>"PHP" is documented <a href="https://php.net">here</a>.</p>

<p>是哪里来的?我不是问过不要在LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD中这样做吗?

无论如何,有人对此有解决方案吗?

php html-parsing
1个回答
0
投票

manual中的注释中对此进行了说明,但似乎没有其他地方;基本上loadHTML在输入HTML中未包含在元素中的任何文本周围添加<p>元素。一种简单的解决方法是将HTML包装在<div>元素中,然后使用substr从输出中删除该<div>

$html = "&quot;PHP&quot; is documented <a href=\"https://php.net\">here</a>.";

$dom = new DOMDocument();
$dom->strictErrorChecking = false;
$dom->preserveWhiteSpace = true;
$dom->loadHTML("<div>$html</div>", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$newHtml = substr($dom->saveHTML(), 5, -7);

echo($newHtml);

输出:

"PHP" is documented <a href="https://php.net">here</a>.

Demo on 3v4l.org

© www.soinside.com 2019 - 2024. All rights reserved.