如何在将XML转换为CSV时获取XML节点名称?

时间:2013-04-23 07:41:46

标签: php xml arrays csv

这是我用来将它转换为csv.which工作正常的代码。

function xml2array($file) {
$string = file_get_contents($file);
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $string, $vals, $index);
xml_parser_free($parser);    
$ary=array();
$i=-1;
foreach ($vals as $r){
    if($r['level'] == 1)continue;
    if($r['level'] == 2 && $r['type'] == "open"){
        ++$i;
        continue;
        }
    $ary[$i][$r['tag']] = @$r['value'];
}
return $ary;
}
$array=xml2array('inventory.xml');
$outstream = fopen('inventory.csv','w');
$header=false;
foreach($array as $k=>$details){
if(!$header){
    fputcsv($outstream,$details);
    $header=true;
}
fputcsv($outstream,$details);
}
fclose($outstream);

问题:我在csv中获取了正确的数据,但没有在我生成的csv中获取XML标题(节点名称)。缺少什么?帮帮我

2 个答案:

答案 0 :(得分:1)

if(!$header){
    fputcsv($outstream,$details);
    $header=true;
}
fputcsv($outstream,$details);

if分支中的fputcsv与无条件分支完全相同,因此它只复制第一行。见http://docs.php.net/array_keys

答案 1 :(得分:1)

我认为你要找的是array_keys(),但应该注意的是,为了使它以这种方式工作,xml中的所有项必须具有完全相同的结构,并且我认为没有嵌套的子节点。如果是这样,这将有效:

function xml2array($file) {
$string = file_get_contents($file);
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $string, $vals, $index);
xml_parser_free($parser);    
$ary=array();
$i=-1;
foreach ($vals as $r){
    if($r['level'] == 1)continue;
    if($r['level'] == 2 && $r['type'] == "open"){
        ++$i;
        continue;
        }
    $ary[$i][$r['tag']] = @$r['value'];
}
return $ary;
}

$array=xml2array('inventory.xml');
$outstream = fopen('inventory.csv','w');
//output the names of the first array item's keys
fputcsv($outstream, array_keys($array[0]));
foreach($array as $k=>$details){
    fputcsv($outstream,$details);
}
fclose($outstream);
相关问题