合并CSV的数组并保留一个标头与PHP

时间:2014-06-05 18:56:27

标签: php csv

我在堆栈溢出处找到了一个脚本,它会将几个csv文件合并到一个csv中,但它不会保留一个头文件。 csv都具有相同的列数,所有标题都相同。如何更改代码以保持只有一个csv的标题,因为它们完全相同?

<?php
   $files_to_merge = array("/csv1/results1.csv", "/csv2/results2.csv", "/csv3/results3.csv");
       $ftm = fopen("merged.csv","w+");
 foreach ($files_to_merge as $file){
     //loop through array
     $fh = fopen("csv/" .$file, "r");
     $line = false;

      while (($data = fgetcsv($fh,8192,",")) != FALSE){
          //ignore first line
          if (!$line){
             //ignore
            $line = TRUE;
          } else {
            fputcsv($ftm,$data,",");
       }
       //write content to new file
  }

fclose($fh);
echo($file . "-". $count . "\n");
//merge the records
endforeach;
fclose($ftm);  

?>

0 个答案:

没有答案