0

我有一个 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

4 回答 4

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);

?>
于 2012-04-11T03:20:11.287 回答
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
)
于 2012-04-11T03:19:23.617 回答
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)
于 2012-04-11T03:33:48.183 回答
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'];
于 2012-04-11T08:26:35.117 回答