Search code examples
phpxmlsimplexml

How to get the last 3 items from an xml file with simpleXml


A bit of a noob when it come s to php and xml but how to get the latest 3 items from a xml file?

$xmlstr= '<?xml version="1.0"?>
<doc>
<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>
...
...
</doc>';

Solution

  • You can use XPath with SimpleXML. The following XPath should return the last 3 tran elements from the XML :

    $xml = simplexml_load_string($xmlstr);
    $result = $xml->xpath("//tran[position() > last()-3]");