简体   繁体   中英

PHP Iterating simplexml in foreach loop

I have a simplexml object which looks as below

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

I want to iterate through it and print only the order number. I use this script:

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

When I do this I get no output from the loop at all, even the "hello" does not print. What am I doing wrong?

Do

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM