2012-05-16 3 views
2

SimpleXML을 사용하여 CSV로 변환하려고하는 다중 레벨 XML 파일이 있습니다.SimpleXML : 다중 레벨 XML 파일 용 XML to CSV

<Products> 
     <Product> 
      <StyleCode>Product Number 1</StyleCode> 
      <Name>Name of Product 1</Name> 
      <Description>Product 1 Is Great</Description> 
      <Categories> 
       <Category>SS-TEES</Category> 
      </Categories> 
      <Items> 
       <Item> 
        <Code>1111122223333444</Code> 
        <Barcode>1111122223333444</Barcode> 
        <Size>2XL</Size> 
        <ShortColour>BLK</ShortColour> 
        <Colour>BLACK</Colour> 
        <Price>39.95</Price> 
        <StockOnHand>6</StockOnHand> 
       </Item> 
       <Item> 
        <Code>0000001427002001</Code> 
        <Barcode>0000001427002001</Barcode> 
        <Size>M</Size> 
        <ShortColour>BLK</ShortColour> 
        <Colour>BLACK</Colour> 
        <Price>39.95</Price> 
        <PriceSpecial>0</PriceSpecial> 
        <StockOnHand>2</StockOnHand> 
       </Item> 
      </Items> 
     </Product> 
     <Product> 
     ....... 
     </Product> 
</Products> 

내가 문제를 CSV이 점을 얻는 데 : 파일 이 같은 것 같습니다. 나는 단순한 1 레벨 XML 파일에 성공했지만 이것이 번거 로움을 입증하고있다.

각 항목에는 해당 제품의 부모 제품 정보가 포함 된 CSV에 고유 한 줄이 있어야합니다.

그래서 CSV의 첫 번째 줄은 등

Product Number 1, Name of Product 1, Product 1 Is Great, SS-TEES, 00000142, 00001427, M, Blk, Black, 39.95, 2 

그리고 것

Product Number 1, Name of Product 1, Product 1 Is Great, SS-TEES, 111222333, 111222333, 2XL, BLK, Black, 39.95, 6 

라인이 될 것이다.

변수 (stylecode, 이름, 설명 등)에 첫 번째 자식을 저장해야한다고 생각하고 항목이있는 동안 첫 번째 자식 변수와 항목을 인쇄하지만 나는 그렇지 않습니다. 그것에 대해 정말로 확신하는 방법.

구조는 전체 문서에서 일관되지만 빈 필드가 있습니다.

답변

0

이 시도 :

<pre><?php 
$sx = simplexml_load_file("test.xml"); 
$new_items = array(); 
foreach($sx->Product as $product){ 
    foreach($product->Items->Item as $item){ 
     array_push($new_items,array(
      "stylecode" => (string)$product->StyleCode, 
      "name" => (string)$product->Name,   
      "description" => (string)$product->Description, 
      "categories" => (string)(is_array($product->Categories))?implode("|",$product->Categories):(string)$product->Categories->Category, 
      "code" => (string)$item->Code,   
      "barcode" => (string)$item->Barcode,    
      "size" => (string)$item->Size,   
      "shortcolor" => (string)$item->ShortColour,   
      "color" => (string)$item->Colour,   
      "price" => (string)$item->Price,    
      "stockonhand" => (string)$item->StockOnHand   
     ));  
    } 
} 

array_walk($new_items,function($element,$key)use(&$new_items){ 
    $new_items[$key]="`".implode("`,`",$element); 
}); 

print_r($new_items);