Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP XPath selecting last matching element [duplicate]

Tags:

php

xpath

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.

like image 514
deab Avatar asked Apr 04 '11 10:04

deab


People also ask

How do I select the last element in XPath?

Locating Strategies- (By XPath- Using last())"last() method" selects the last element (of mentioned type) out of all input element present.

How do you select the first element in XPath?

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 .

How use contains XPath?

The syntax for locating elements through XPath- Using contains() method can be written as: //<HTML tag>[contains(@attribute_name,'attribute_value')]


1 Answers

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; } 
like image 184
VolkerK Avatar answered Sep 21 '22 18:09

VolkerK