Possible Duplicates:
PHP SimpleXML. How to get the last item?
XSLT Select all nodes containing a specific substring
I need to find the contents of the last span element with a class of 'myClass'. I've tried various combinations but can't find the answer.
//span[@class='myPrice' and position()=last()]
This returns all the elements with class 'myClass', I'm guessing this is because each found element is the last at the time of processing - but I just need the actual last matching element.
Locating Strategies- (By XPath- Using last())"last() method" selects the last element (of mentioned type) out of all input element present.
Parentheses works! You can also add more path after (..)[ 1], like: '(//div[text() = "'+ name +'"])[1]/following-sibling::*/div/text()' . In case there are many nodes matches name .
The syntax for locating elements through XPath- Using contains() method can be written as: //<HTML tag>[contains(@attribute_name,'attribute_value')]
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With