ufucuk
ufucuk

Reputation: 475

DomXPath Selecting

I have a problem with the DomXPath for selecting what I need. I have a structure like

<div id="a">
  Something
    <nobr> Inside </nobr>
</div>

What I want is to select only 'Something' not 'Inside'. I know how to select only 'Inside' or both of them in the same time like //div[@id='a'] and then call $obj->nodeValue, but I couldn't find a way to select only 'Something'. Could anyone help me about this? Thanks.

Edit: If Something is changed to Something 123456 can you also give me a hint how to select only numeric values as 123456 as a bonus?

Upvotes: 1

Views: 699

Answers (1)

hakre
hakre

Reputation: 197757

To locate the number inside the text node in xpath is quite heavy. Instead you can use a regular expression in PHP to parse the textnode's text to obtain the value:

$doc = new DomDocument;
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
$text = $xpath->query("/div[@id='a']/child::text()")->item(0)->nodeValue;
$r = preg_match('~\d+~', $text, $matches);
list($number) = $matches;

Demo

Upvotes: 1

Related Questions