PHP在foreach循环中迭代simplexml

时间:2013-04-02 02:33:14

标签: php xml loops 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”也没有打印。我做错了什么?

1 个答案:

答案 0 :(得分:2)

待办事项

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