PHP XPath selecting last matching element

28,744

Solution 1

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;
}

Solution 2

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.

Share:
28,744
Admin
Author by

Admin

Updated on July 17, 2020

Comments

  • Admin
    Admin almost 4 years

    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.