Wednesday, 17 December 2014

How to append csv file in php

<?php



function joinFiles(array $files, $result) {

$fp = fopen($result, "w");
$l=0;
foreach($files as $csv) {
  $row = 1;
  if (($handle = fopen($csv, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, " ", ",")) !== FALSE) {
$line=array();
$datacount = count($data);
        // Add the data from the read csv file to the output array
if($l==0){
for($j=0;$j<$datacount;$j++){
$line[]=$data[$j];
}
fputcsv($fp, $line);
}else{
        if($row!=1){
for($j=0;$j<$datacount;$j++){
$line[]=$data[$j];
}
fputcsv($fp, $line);
}
}
      $row++;
    }
    fclose($handle);
  }
  $l++;
}
}

//Call function
joinFiles(array('csv1.csv', 'csv2.csv','csv3.csv'), 'finalcsv.csv');

?>

No comments :

Post a Comment