PHP XPath选择最后一个匹配元素 [英] PHP XPath selecting last matching element

查看:219
本文介绍了PHP XPath选择最后一个匹配元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:
PHP SimpleXML.如何获得最后一件商品?
XSLT选择所有包含特定子字符串的节点

Possible Duplicates:
PHP SimpleXML. How to get the last item?
XSLT Select all nodes containing a specific substring

我需要使用"myClass"类查找最后一个span元素的内容.我尝试了各种组合,但找不到答案.

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()]

这将返回所有带有"myClass"类的元素,我猜这是因为每个找到的元素在处理时都是最后一个元素-但我只需要实际的最后一个匹配元素即可.

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.

推荐答案

您必须为要标记//span[@class='myPrice']的处理器标记为当前集合,然后将谓词position()= last()应用于该处理器.设置.

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()]

例如

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

这篇关于PHP XPath选择最后一个匹配元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆