2

我有一个多级 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 文件上取得了成功,但这证明有些麻烦。

每个项目都应该在 CSV 中有自己的行,其中包含来自其父产品的信息。

所以 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

等等。

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

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

4

1 回答 1

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);
于 2012-05-17T00:33:59.970 回答