如何读取 SimpleXMLElement 中特定数量的代码

How to read specific amounts of code in a SimpleXMLElement

我正在尝试读取 SimpleXMLElement/XML 文件的一部分。 问题是无论如何我都无法获得想要的文本。

我尝试调试我拥有的 XML,所以我这样打印:

 foreach($response->items as $item) {
                   fwrite($file, var_export($item, TRUE));
               }

输出

SimpleXMLElement::__set_state(array( 'item' => array ( 0 => SimpleXMLElement::__set_state(array( 'id' => '000-1', 'description' => 'Notebook Prata', 'quantity' => '1', 'amount' => '1830.00', )), 1 => SimpleXMLElement::__set_state(array( 'id' => 'AB01', 'description' => 'Notebook Preto', 'quantity' => '2', 'amount' => '1340.00', )), ), ))

但是当我尝试检索特定项目中的数据时,return 是空的。 我尝试了以下方法:

fwrite($file, $item->amount);
//
fwrite($file, $item->{'amount'});
//
fwrite($file, $items->$item->amount);

但似乎没有任何效果。

如何更正语法以获得预期的结果?我希望文件写有“1830.00”和“1340.00”,但我只得到空白。

XML LIKE THIS FOR REFERENCE

如果你用英语阅读这似乎合乎逻辑的事实,你被愚弄了:

foreach($response->items as $item) {

但它与XML的结构不匹配。

考虑这个 XML:

<?xml version="1.0"?><a>
    <b>
        <c>first C</c>
        <c>second C</c>
    </b>
</a>

如果 $response 是整个文档 (<a>...</a>),那么要访问每个 <c>,您需要这样做:

foreach($response->b->c as $c)

您的 XML 具有相同的结构:

<?xml version="1.0"?><transaction>
    ...
    <items>
        <item>first item</item>
        <item>second item</item>
    </items>
    ...
</transaction>

所以你的循环需要是:

foreach($response->items->item as $item)

然后 <item> 的子项将如您所料可用,例如 <amount>:

echo $item->amount;