PHP: How to access the last element of an XML file

advertisements

I have an XML file that I want to be able to access the last element in the file. (NOTE: the file is dynamically updated and the latest values are always in the latest element:

<?xml version="1.0"?>

<tran>
    <balance>25000</balance>
    <amount>560</amount>

</tran>

<tran>
    <amount>5999</amount>
    <balance>30999</balance>
</tran>
<tran>
    <amount>5000</amount>
    <balance>20000</balance>
</tran>
<tran>
    <amount>8923</amount>
    <balance>25000</balance>
</tran>

I want to be able to access that last node.

How can I do this using Php Simple XML?

Thanks


Firstly your XML needs a parent node (in the example below I've inserted 'trans' element) Then try this xpath:

<?php
$xmlstr=<<<EOXML
<?xml version="1.0"?>
<trans>
<tran>
    <balance>25000</balance>
    <amount>560</amount>

</tran>

<tran>
    <amount>5999</amount>
    <balance>30999</balance>
</tran>
<tran>
    <amount>5000</amount>
    <balance>20000</balance>
</tran>
<tran>
    <amount>8923</amount>
    <balance>25000</balance>
</tran>
</trans>
EOXML;

$xml =new SimpleXMLElement($xmlstr);
$last = $xml->xpath("/trans/tran[last()]");
var_dump($last);

?>