-1

这是我用来将其转换为 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 标头(节点名称)。缺少什么?帮帮我

4

2 回答 2

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

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

于 2013-04-23T07:50:32.673 回答
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);
于 2013-04-23T08:34:29.713 回答