1

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?

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I've edited the response. SalesInvoices (plural) is the root element so it does not need to be pathed out. Since all that it contains is the SaleInvoice elements you can just foreach($xml directly
foreach( $xml->SalesInvoice ... (singular) would also have worked. The important thing to remember is that $xml represents the root node, not an abstract Document object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.