简体   繁体   中英

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

I have this in my html (multiple instances of the following):

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

I want to get this:

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

Using

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

I am getting

This is the first line

and

This is the second line

as separate nodes.

As per another question I tried

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

But that gives and 'Invalid Expression' error.

Can someone help me out with what I'm doing wrong here?

Thanks.

You can get the node() but excluding the a element:

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

Demo (using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM