2014-09-23 94 views
0

所以我有這個XML,我試圖通過SimpleXML類的PHP讀取。通過php讀取XML

<ns0:ASN xmlns:ns0="http://schemas.microsoft.com/dynamics/2008/01/documents/ASN"> 
<CustPackingSlipJour xmlns="http://schemas.microsoft.com/dynamics/2008/01/documents/ASN" class="entity"> 
<BON_FileNameSeqNum>4</BON_FileNameSeqNum> 
<!-- funktionell: Internt löpnr --> 
<BON_TotalNetAmount>726.00</BON_TotalNetAmount> 
<!-- funktionell: Totalt belopp --> 
<BON_TotalTaxAmount>181.50</BON_TotalTaxAmount> 
<!-- funktionell: Momsbelopp --> 
<InvoiceAccount>9001</InvoiceAccount> 
<!-- funktionell: --> 
<LanguageId>SV</LanguageId> 
<!-- funktionell: Språk --> 
<OrderAccount>9001</OrderAccount> 
<!-- funktionell: Butiks nr för intern användning! --> 
<Qty>4.00</Qty> 
<!-- funktionell: Total lev kvant! --> 
<SalesId>24</SalesId> 
<!-- funktionell:Försäljningsordernr! --> 
<CustPackingSlipTrans class="entity"> 
<BON_LineNetAmount>149.00</BON_LineNetAmount> 
<!-- funktionell: Orderradsbelopp! --> 
<BON_SalesPrice>0.00</BON_SalesPrice> 
<!-- funktionell: Försäljningspris! --> 
<DeliveryDate>2014-09-09</DeliveryDate> 
<!-- funktionell: Leveransdag! --> 
<ItemId>10001</ItemId> 
<!-- funktionell: Artikelnr! --> 
<Ordered>1.00</Ordered> 
<!-- funktionell:Beställd kvantitet! --> 
<PackingSlipId>00000004_061</PackingSlipId> 
<!-- funktionell: --> 
<Qty>1.00</Qty> 
<!-- funktionell:Levererad kvantitet! --> 
<InventReportDimHistory class="entity"> 
<InventDim class="entity"/> 
</InventReportDimHistory> 
</CustPackingSlipTrans> 

我試圖訪問它的代碼元素: -

<?php 
$asn=simplexml_load_file("ASN.xml"); 
echo $asn->CustPackingSlipTrans[0]->ItemId; 
?> 

但這似乎並不奏效。我得到一個空白輸出。我已經閱讀了一些關於Simplexml類的教程,並達成了這段代碼。但我不確定我在這裏做了什麼錯。 我將如何訪問XML的每個元素?

所有的建議表示讚賞。

回答

0

如果你的XML是正確的縮進,你會看到它的:

<CustPackingSlipJour ...> 
    ... 
    <CustPackingSlipTrans ...> 
     ... 
     <ItemId>10001</ItemId> 

所以,你的代碼應該是:

echo $asn->CustPackingSlipJour[0]->CustPackingSlipTrans[0]->ItemId; 
     ^^^^^^^^^^^^^^^^^^^^^^^^ 
1

你應該總是嘗試,並按照這個順序: -

echo $objectname->parentname->childname->subchild 

這總是有效的。但是,您應該始終使用縮進的XML。這是主要要求。如果你有縮進,你可以很容易地看到哪個是父元素,哪個是孩子。