2013-04-02 235 views
1

PHP迭代的SimpleXML我有SimpleXML對象看起來如下在foreach循環

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

當我做到這一點我沒有得到任何輸出循環可言,甚至連「你好」不打印。我究竟做錯了什麼?

回答

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; 
} 
+0

感謝您的回覆,遺憾的是不工作 –

+0

我編輯的迴應。 SalesInvoices(複數)是根元素,所以它不需要被打散。因爲它包含的所有是SaleInvoice元素你可以'的foreach($ xml'直接 – jcbwlkr

+0

謝謝你的好先生,我現在的生活是值得的再次 –