PHP:如何访问XML文件中的最后一个元素

时间:2012-04-11 03:09:02

标签: php xml arrays

我有一个XML文件,我希望能够访问文件中的最后一个元素。 (注意:文件是动态更新的,最新值始终在最新元素中:

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

我希望能够访问最后一个节点。

如何使用Php Simple XML执行此操作?

由于

4 个答案:

答案 0 :(得分:3)

首先你的XML需要父节点(在下面的示例中我插入了'trans'元素) 然后尝试这个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);

?>

答案 1 :(得分:0)

试试这个:

<?php
    $xmlstr = <<<XML
    <?xml version="1.0"?>
    <transactions>
        <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>
    </transactions>
    XML;

    $elements = new SimpleXMLElement($xmlstr);

    $last_element = $elements->tran[count($elements)-1];

    print_r($last_element);

?>

输出

SimpleXMLElement Object
(
    [amount] => 8923
    [balance] => 25000
)

答案 2 :(得分:0)

尝试

$xmlString = '<?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>';

$xml = simplexml_load_string($xmlString);
$var = end($xml);
$var = end($var);
var_dump($var);

输出

object(SimpleXMLElement)[5]
  public 'amount' => string '8923' (length=4)
  public 'balance' => string '25000' (length=5)

答案 3 :(得分:0)

您可以简单地计算“tran”元素

//value of $i is the total count of tran element in xml
$last_element_amount  = $xml->tran[$i]['amount'];
$last_element_balance  = $xml->tran[$i]['balance'];