使用fputcsv的另一个PHP - XML到CSV转换问题

时间:2014-02-09 16:15:02

标签: php xml csv fputcsv

我在一个问题上需要一些帮助:我正在使用PHP脚本将XML转换为CSV,但我有一个问题,它们是属性中的属性。

这是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文件中获取所有这些功能。 任何帮助将不胜感激。

提前致谢!

1 个答案:

答案 0 :(得分:0)

CSV不适合那种嵌套数据。

要么你必须创建两个csv文件:prodcuts.csvfeatures.csvfeatures.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,因为它最适合嵌套数据。

相关问题