2016-11-17 211 views
0

我一直在試圖解析這個數據一段時間,但我真的不明白simpleXML以及它如何存儲/檢索。我有以下的XML:解析兒童Simplexml兒童

<ListOrderItemsResult> 
    <OrderItems> 
     <OrderItem> 
     <QuantityOrdered>1</QuantityOrdered> 
     <Title>Organic Chamomile &amp; Lavender Shea Butter CP Soap Making Kit 2 Lbs.</Title> 
     <ItemPrice> 
      <CurrencyCode>USD</CurrencyCode> 
      <Amount>29.99</Amount> 
     </ItemPrice> 
     <ItemTax> 
      <CurrencyCode>USD</CurrencyCode> 
      <Amount>0.00</Amount> 
     </ItemTax> 
     </OrderItem> 
     <OrderItem> 
     <QuantityOrdered>1</QuantityOrdered> 
     <Title>Eucalyptus &amp; Mint Organic Shea Butter CP Soap Making Kit 3 lbs.</Title> 
     <ItemPrice> 
      <CurrencyCode>USD</CurrencyCode> 
      <Amount>32.99</Amount> 
     </ItemPrice> 
     <ItemTax> 
      <CurrencyCode>USD</CurrencyCode> 
      <Amount>0.00</Amount> 
     </ItemTax> 
     </ShippingDiscount> 
     </OrderItem> 
    </OrderItems> 
    <AmazonOrderId>12134</AmazonOrderId> 
    </ListOrderItemsResult> 

我想將它轉換成每個OrderItem是一行的csv。這些列是:QuantityOrdered,Title,ItemPrice,ItemTax。到目前爲止,我設法抓住了除ItemPrice和ItemTax之外的所有東西,因爲他們有子節點,我不知道如何訪問它們。

這裏是我的代碼:

$OrderItem = $xmlDocs->xpath('//a:OrderItem'); 

的foreach($ OrderItem的爲$ n){

foreach ($AmazonOrderId as $t) { 
    $row[]=$t; 
    } 
    // Iterate through each child of <OrderItem> node 
    $child = $xml->xpath('//a:OrderItem['.$i.']/*'); 



    foreach ($child as $value) { 
    $row[] = $value; 
    } 
    print_r($row); 



    $fs = fopen('141.csv', 'a'); 
    fputcsv($fs, $row);  

    $row = []; 
    // Clean out array for next <item> (i.e., row) 
    $i++;   // Move to next <item> (i.e., node position) 

}

FCLOSE($ FS);

我有它的工作,但它是因爲我無法弄清楚如何到達孩子的孩子,什麼都沒有顯示ItemPrice和ItemTax。

TL; DR - 我試圖循環訪問每個OrderItem節點並獲取每個子節點的值,如果子節點有子節點,我只想獲取名爲'Amount'的節點的值。

回答

0

我想出瞭如何做到這一點。我必須真正分解simplexml以瞭解對象層如何以便我可以弄清楚如何提取我想要的數據。我們希望,這是有道理的人,但是當你試圖從SimpleXML對象的特定值,你想讓它這樣看,當你的print_r():

SimpleXMLElement Object 
    (
     [0] => 0 //0 being the value you want - you can now add this to whatever variable you want once you have it down to this. 
    ) 

這裏是做的代碼它:

//Iterate through the first node <OrderItem> 
foreach ($OrderItem as $n) {   

    //Add the AmazonOrderId to the start of each line 
    foreach ($AmazonOrderId as $t) { 
    $row[]=$t; 
    } 

    $child = $xml->xpath('//a:OrderItem['.$i.']/*'); 
    // Iterate through each child of <OrderItem> node 
    foreach ($child as $value) { 
    //If the child has an attribute named <Amount> 
    if($value->Amount[0]){ 
     //Iterate through and grab the value of <Amount> and post add to $row 
     foreach ($value->Amount as $t) { 
     $row[] = $t; 
     } 
    } 
    //Else add the value to $row 
    else { 
     $row[] = $value; 
    } 
} 


$fs = fopen('141.csv', 'a'); 
fputcsv($fs, $row); 
$row = []; 
$i++; 
} 
fclose($fs);