PHP SimpleXML.如何获得最后的物品? [英] PHP SimpleXML. How to get the last item?

查看:68
本文介绍了PHP SimpleXML.如何获得最后的物品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获取simplexml对象中的最后一个项目(或与此相关的任何特定项目)?假设您不知道会有多少个节点.

How would I get the last item (or any specific item for that matter) in a simplexml object? Assume you don't know how many nodes there will be.

例如.

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="/xsl.xml"?>
<obj 
  href="http://xml.foo.com/" 
  display="com.foo.bar" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns="http://obix.org/ns/schema/1.0" 
>
 <list name="data" of="HistoryRecord">
  <obj>
   <abstime name="timestamp" val="1876-11-10T00:00:00-08:00"></abstime>
   <int name="energy_in_kwh" val="1234"></int>
   <int name="energy_out_kwh" val="123456"></int>
  </obj>
  <obj>
   <abstime name="timestamp" val="1876-11-10T00:15:00-08:00"></abstime>
   <int name="energy_in_kwh" val="1335"></int>
   <int name="energy_out_kwh" val="443321"></int>
  </obj>
 </list>
 <int name="count" val="2"></int>
</obj>

我想获取最后一个<obj></obj>块(甚至只是其中的一部分).

And I want to grab the last <obj></obj> chunk (or even just part of it).

推荐答案

使用XPath的last()函数可以解决此问题:

Use XPath's last() function, which solves this very problem:

<?php 
$xml = simplexml_load_file('HistoryRecord.xml'); 
$xml->registerXPathNamespace('o', 'http://obix.org/ns/schema/1.0');

$xpath = "/o:obj/o:list/o:obj[last()]/o:int[@name = 'energy_in_kwh']";
$last_kwh = $xml->xpath($xpath); 
?> 

在这里查找最后一个内部<obj>,并在其中查找名称为"energy_in_kwh"<int>.

Here it looks for the last inner <obj>, and therein for the <int> with the name of "energy_in_kwh".

当心名称空间注册. (您所有的元素都是"http://obix.org/ns/schema/1.0"命名空间的一部分,XPath查询必须反映出这一点.

Watch out for the namespace registration. (All your elements are part of the "http://obix.org/ns/schema/1.0" namespace, the XPath query must reflect that.

请注意,[last()]等同于[position() = last()].

这篇关于PHP SimpleXML.如何获得最后的物品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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