2014-02-09 46 views
1

我需要一些问题的帮助:我正在使用PHP脚本将XML转换为CSV,但我有这个问题,他们是属性中的属性。另一个PHP - XML到CSV转换问题与fputcsv

这是XML文件的结构:

<Products> 
<Product> 
    <Name> 
    SomeProductName 
    </Name> 
    <Colour> 
    Black 
    </Colour> 
    <Features> 
    <Feature_0> 
    this is feature 0 
    </Feature_0> 
    <Feature_1> 
    this is feature 1 
    </Feature_1> 
    <Feature_2> 
    this is feature 1 
    </Feature_2> 
    </Features> 
<Product> 
</Product> 

,这是我的脚本:

{$filexml='product.xml'; 
if (file_exists($filexml)) { 
    $xml = simplexml_load_file($filexml); 
    $f = fopen('product.csv', 'w'); 
foreach($xml->Products->Product as $product) {  
    $values = array(
    "Name" => $product->Name, 
    "Colour" => $product->Colour, 
    "Features" => $product->Features); 
    fputcsv($f, $values,',','"'); 
    } 
fclose($f); 
} 

这个剧本我只得到Feature_0,我需要让我的CSV所有这些功能文件。 任何帮助将不胜感激。

在此先感谢!

回答

0

CSV并不适合这种嵌套数据。

要么你就必须创建两个CSV文件:prodcuts.csvfeatures.csv其中来自features.csv指向项条目products.csv,像关系数据库或你就必须在功能列表压扁成一个单一的字符串,使CSV应该是这样的:

"product_name", "product_color", "features" 
"SomeProductName", "Black", "this is feature 0|this is feature 1|this is feature 2" 
"AnotherProductName", "White", "this is feature foo|this is feature bar" 

然而,扁平化的功能必须确保的分隔符不是数据本身的一部分。

我鼓励你保留它xml,因为它最适合嵌套数据。

+0

谢谢,回答我的问题。我想,我会保留它作为一个很好的解决方案xml现在只是。因为我对平坦化/合并这两个.csv不太了解。再次感谢你 –

+0

欢迎:) – hek2mgl