PHP在foreach循环中迭代simplexml

我有一个simplexml对象,如下所示

<?xml version="1.0"?>
<SalesInvoices xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://api.unleashedsoftware.com/version/1">
    <SalesInvoice>
        <OrderNumber>100</OrderNumber>
    </SalesInvoice>
    <SalesInvoice>
        <OrderNumber>101</OrderNumber>
    </SalesInvoice>
</SalesInvoices>

我想遍历它并仅打印订单号.我使用以下脚本:

foreach ($xml->SalesInvoices->SalesInvoice as $salesinvoice) {
    echo "hello";
    echo $salesinvoice->OrderNumber;
}

当我这样做时,我根本没有从循环中获得任何输出,即使“ hello”也不会打印.我究竟做错了什么?

解决方法:

<?php

$string = '<?xml version="1.0"?>
<SalesInvoices xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://api.unleashedsoftware.com/version/1">
    <SalesInvoice>
        <OrderNumber>100</OrderNumber>
    </SalesInvoice>
    <SalesInvoice>
        <OrderNumber>101</OrderNumber>
    </SalesInvoice>
</SalesInvoices>';
$xml = simplexml_load_string($string);

foreach($xml as $SalesInvoice) {
    print $SalesInvoice->OrderNumber;
}
上一篇:JavaScript中的带有break vs find()的for循环


下一篇:在python中使用enumerate()时从列表中删除元素