首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SimpleXML到CSV,写入CSV报头?

SimpleXML到CSV,写入CSV报头?
EN

Stack Overflow用户
提问于 2012-10-14 09:07:20
回答 1查看 1.6K关注 0票数 1

我有一个简单的小脚本,获取XML并将其转换为CSV。然而,它并不写入头。有人知道如何写标题吗?

代码语言:javascript
复制
$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>的子元素的所有内容放在精美的列中。但是它不会将元素名称写为CSV标题。

你知道我怎么才能编辑脚本,让它也包含头部吗?

谢谢

麦克

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-14 09:48:18

您可以使用SimpleXMLElement::getName()函数从第一组数据中获取元素名称,并使用该名称写入CSV header。

代码语言:javascript
复制
$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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12878455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档