【问题标题】:Another PHP - XML to CSV conversion issue With fputcsv另一个 PHP - 使用 fputcsv 的 XML 到 CSV 转换问题
【发布时间】:2014-02-09 16:15:01
【问题描述】:

我需要一些帮助来解决一个问题:我正在使用 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 文件中获得所有这些特征。 任何帮助将不胜感激。

提前致谢!

【问题讨论】:

    标签: php xml csv fputcsv


    【解决方案1】:

    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"
    

    但是,flatten 函数必须确保分隔符不是数据本身的一部分。

    我建议您保留它xml,因为它最适合嵌套数据。

    【讨论】:

    • 感谢您回答我的问题。我想,我现在就将它保留为 xml 作为我的一个很好的解决方案。因为我对展平/组合这两个.csv不太了解。再次感谢您
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    相关资源
    最近更新 更多