我有一个简单的小脚本,获取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>的子元素的所有内容放在精美的列中。但是它不会将元素名称写为CSV标题。
你知道我怎么才能编辑脚本,让它也包含头部吗?
谢谢
麦克
发布于 2012-10-14 09:48:18
您可以使用SimpleXMLElement::getName()函数从第一组数据中获取元素名称,并使用该名称写入CSV header。
$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);
}https://stackoverflow.com/questions/12878455
复制相似问题