PHP+XPath - 获取包含 <br> 的节点文本,不带子节点内容


PHP+XPath - Get node text including <br>, without child nodes content

我的html中有这个(以下的多个实例):

<div id='message'>
    This is the first line<br />
    This is the second line
    <a href='link'>link_A</a>
</div>

我想得到这个:

This is the first line<br />This is the second line

$messages = $xpath->query('//div[@id="message"]/text()');

我正在得到

这是第一行

这是第二行

作为单独的节点。

根据我尝试过的另一个问题

$xpath->query('//div[@id="message"][self::text() or self:br]');
AND
$xpath->query('//div[@id="message"]//nodes[self::text() or self:br]');

但这给出了"无效表达式"错误。

有人可以帮助我解决我在这里做错了什么吗?

谢谢。

您可以获取node()但不包括a元素:

//div[@id="message"]/node()[not(self::a)]

演示(使用xmllint):

$ cat test.html
<div id='message'>
    This is the first line<br/>
    This is the second line
    <a href='link'>link_A</a>
</div>
$ xmllint test.html --xpath '//div[@id="message"]/node()[not(self::a)]'
This is the first line<br/>
This is the second line