SimpleXML:用于多级XML文件的XML到CSV

时间:2012-05-16 23:11:38

标签: php xml xml-parsing simplexml

我有一个多级XML文件,我正在尝试使用SimpleXML转换为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文件,但这证明有些麻烦。

每个ITEM都应在CSV上拥有自己的行,其中包含来自其父级PRODUCT的信息。

所以CSV的第一行是

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

第2行将是

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

等等。

我想我需要将产品第一个孩子存放在一个变量(样式,名称,描述等)中,然后在有一个项目时,打印第一个子变量,然后打印项目,但我不是真的确定如何去做。

结构在整个文档中是一致的,但是有空白字段。

1 个答案:

答案 0 :(得分: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);