1

我有一个简单的小脚本,它可以抓取 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 标题。

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

谢谢

麦克风

4

1 回答 1

2

您可以使用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);
}
于 2012-10-14T01:48:18.143 回答