【问题标题】:SimpleXML to CSV, writing CSV headers?SimpleXML 到 CSV,编写 CSV 标头?
【发布时间】:2012-10-14 01:07:19
【问题描述】:

我有一个简单的小脚本,它可以抓取 XML 并将其转换为 CSV。但是它不写标题。有谁知道标题怎么写?

$file='example.xml';
if (file_exists($file)) {
    $xml = simplexml_load_file($file);
    $f = fopen('newfile.csv', 'w');
    foreach ($xml->Information as $information) {
        fputcsv($f, get_object_vars($information),',','"');
    }
    fclose($f);
}

这会将<Information> 的子元素的所有内容放在 Excel 的漂亮列中。但它不会将元素名称写为 CSV 标题。

有什么想法可以编辑脚本以包含标题吗?

谢谢

迈克

【问题讨论】:

    标签: php xml csv simplexml fopen


    【解决方案1】:

    您可以使用SimpleXMLElement::getName() 函数从第一组数据中获取元素名称,并使用它来编写 CSV 标头。

    $file='example.xml';
    if (file_exists($file)) {
        $xml = simplexml_load_file($file);
        $f = fopen('newfile.csv', 'w');
    
        // array to hold the field names
        $headers = array(); 
        // loop through the first set of fields to get names
        foreach ($xml->Information->children() as $field) { 
            // put the field name into array
            $headers[] = $field->getName(); 
        }
        // print headers to CSV
        fputcsv($f, $headers, ',', '"');
    
        foreach ($xml->Information as $information) {
            fputcsv($f, get_object_vars($information), ',', '"');
        }
        fclose($f);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-11
      • 1970-01-01
      • 2017-02-24
      • 2015-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      相关资源
      最近更新 更多