PHP XPath selecting last matching element
You have to mark for the processor that you want to treat //span[@class='myPrice']
as the current set and then apply the predicate position()=last() to that set.
(//span[@class='myPrice'])[last()]
e.g.
<?php
$doc = getDoc();
$xpath = new DOMXPath($doc);
foreach( $xpath->query("(//span[@class='myPrice'])[last()]") as $n ) {
echo $n->nodeValue, "\n";
}
function getDoc() {
$doc = new DOMDOcument;
$doc->loadxml( <<< eox
<foo>
<span class="myPrice">1</span>
<span class="yourPrice">0</span>
<bar>
<span class="myPrice">4</span>
<span class="yourPrice">99</span>
</bar>
<bar>
<span class="myPrice">9</span>
</bar>
</foo>
eox
);
return $doc;
}
The expression you used means "select every span element provided that (a) it has @class='myprice'
, and (b) it is the last child of its parent. There are two errors:
(1) you need to apply the filter [position()=last()]
after filtering by @class, rather than applying it to all span elements
(2) an expression of the form //span[last()]
means /descendant-or-self::*/(child::span[last()])
which selects the last child span of every element. You need to use parentheses to change the precedence: (//span)[last()]
.
So the expression becomes (//span[@class='myPrice'])[last()]
as given by VolkerK.