I have multiple .csv file with the same column. I wanna merge them to a new .csv file. But i get empty file .csv

For example, i have three files:

CSV 1:

ID,name,age
1,Andy,18
2,Mary,19
3,Buddy,19
...

CSV 2:

ID,name,age
5,Andy,18
6,Cindy,20
...

CSV 3:

ID,name,age
9,Mody,18
10,Trudy,20
15,Windy,20
17,Somebody,22
...

There is result i want:

ID,name,age
1,Andy,18
2,Mary,19
3,Buddy,19
5,Andy,18
6,Cindy,20
9,Mody,18
10,Trudy,20
15,Windy,20
17,Somebody,22

I try with my code but it give me empty file:

$handle = fopen($file, "r");
$data = fgetcsv($handle, 0, ",");
fclose($handle);
$name = $_SERVER["DOCUMENT_ROOT"].'pathfile.csv';
$fopen = fopen($name, 'a');
fputcsv($fopen,$data,',','');
fclose($fopen);
up vote 0 down vote accepted
<?php
function joinFiles(array $files, $result) {
if(!is_array($files)) {
throw new Exception('`$files` must be an array');
}
$wH = fopen($result, "w+");
foreach($files as $file) {
$fh = fopen($file, "r");
while(!feof($fh)) {
fwrite($wH, fgets($fh));
}
fclose($fh);
unset($fh);
fwrite($wH, "\n"); //usually last line doesn't have a newline
}
fclose($wH);
unset($wH);
}?>

USAGE:

<?php
joinFiles(array('join1.csv', 'join2.csv'), 'join3.csv');?>

After combining you can easily sort

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.