D
D
Devate2016-04-05 04:58:59
XPath
Devate, 2016-04-05 04:58:59

XPath: how to get a text node when there are tags next to it?

Hello!
I started learning XPath, a very cool thing, but it stuck out of the blue ... There is a code:

$xml = simplexml_load_string('<div>123 <br /> 456</div>');

I want to get text nodes from here - 123 and 456. So that everything is separate. I try:
$xml->xpath('//div/text()[1]')
I get the entire text :( Is it possible to get separate text nodes? Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DevMan, 2016-04-05
@Devate

$dom = new DOMDocument;
$dom->loadXML('<div>123 <br /> 456</div>');

$xpath = new DOMXPath($dom);
foreach ($xpath->query('//div/text()') as $textNode) {
  echo trim($textNode->nodeValue), PHP_EOL;
}
ideone.com/FYkZwX

K
krypt3r, 2016-04-05
@krypt3r

XPath substring*() functions or PHP tools

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question