2016-11-17 209 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);