Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在将XML转换为CSV时获取XML节点名称?_Php_Xml_Arrays_Csv - Fatal编程技术网

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

Php 如何在将XML转换为CSV时获取XML节点名称?,php,xml,arrays,csv,Php,Xml,Arrays,Csv,下面是我用来将其转换为csv的代码,效果很好 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(

下面是我用来将其转换为csv的代码,效果很好

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头(节点名称)。缺少什么?请帮助我

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

if分支中的
fputcsv
与无条件分支的作用完全相同,因此它只复制第一行。请参见

我认为您要查找的是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);

嗨,Stack Overflow并不是复制粘贴代码的修复站。要求提问者表现出他们自己的一些努力。@佩卡,这是我的努力,先生。我需要的是知道我在检索标题值方面的错误。Thanxyup,它也在做同样的事情。我正在修改它。thanx用于响应