首页 > 解决方案 > xpath php - LIBXML_HTML_NOIMPLIED 的问题

问题描述

我正在尝试在文档中查找所有 p 标签,如下所示:

$dom = new DOMDocument();
$html = '<p>First</p><p>Second</p><p>Third</p><h3>Test 2</h3><p>Fourth</p>';
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$itens = [];
$xp = new DOMXPath($dom);

$res = $xp->query('//p');
foreach ($res as $item) {
    $itens[] = $item->nodeValue;
}

print_r($itens);

但是当 LIBXML_HTML_NOIMPLIED 打开时,它不能按预期工作。我得到:

Array
(
    [0] => FirstSecondThirdTest 2Fourth
    [1] => Second
    [2] => Third
    [3] => Fourth
)

但我希望:

Array
(
    [0] => First
    [1] => Second
    [2] => Third
    [3] => Fourth
)

这里发生了什么?

标签: phpdomxpath

解决方案


问题是您的 HTML 实际上是一个文档片段,因为它没有单个根节点。 loadHTML()试图解决这个问题,你可以看看你是否这样做

echo $dom->saveHTML();

你得到

<p>First<p>Second</p><p>Third</p><h3>Test 2</h3><p>Fourth</p></p>

一个简单的解决方法是<div>在加载之前向源添加一个基本标签(我使用 a )......

$dom->loadHTML("<div>$html</div>", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

这使....

Array
(
    [0] => First
    [1] => Second
    [2] => Third
    [3] => Fourth
)

推荐阅读