2013-04-23 62 views
-1

這裏是我用來將它轉換爲csv.which工作正常的代碼。如何在將XML轉換爲CSV時獲取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'); 
$header=false; 
foreach($array as $k=>$details){ 
if(!$header){ 
    fputcsv($outstream,$details); 
    $header=true; 
} 
fputcsv($outstream,$details); 
} 
fclose($outstream); 

問題:我在我的生成csv.What得到適當的數據以csv,但沒有得到XML頭(節點名稱)缺少幫我

+0

嗨,堆棧溢出是不是一個真正的複製和粘貼代碼的維修站。希望看到他們自己的努力。 – 2013-04-23 07:46:49

+1

@pekka這就是我的努力先生。我需要什麼是需要知道我在哪裏檢索標題值錯誤。感謝 – CodePlayer 2013-04-23 07:51:22

回答

1

我認爲你正在尋找的是array_keys(),但應該注意的是,爲了使它以這種方式工作,xml中的所有項必須具有完全相同的結構,並且沒有嵌套的childnodes,我相信。如果是這樣,這將工作:

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); 
+0

thanx.it工作 – CodePlayer 2013-04-23 09:33:07

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

fputcsv在if-branch和無條件的完全一樣,所以它只是複製第一行。請參閱http://docs.php.net/array_keys

+0

是的,它做同樣的。我正在修改它.thanx的響應 – CodePlayer 2013-04-23 08:11:00