读取多个CSV文件并将其写入新的CSV文件php

时间:2016-03-17 03:55:47

标签: php

我有多个具有相同列的.csv文件。我想将它们合并到一个新的.csv文件中。但我得到空档.csv

例如,我有三个文件:

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
...

我想要的结果是:

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

我尝试使用我的代码,但它给了我空文件:

$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);

1 个答案:

答案 0 :(得分:0)

<?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);
}?>

用法:

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

合并后,您可以轻松排序