ihsansat ihsansat - 4 months ago 37
PHP Question

How can I merge 3 CSV files into 1 CSV file using PHP?

I want to merge 3 csv files, each file is :

File1.csv :
2014-01-01,10
2014-01-02,15
2014-01-03,25
.
.
.

File2.csv :
2014-01-01,20
2014-01-02,26
2014-01-03,46
.
.
.

File3.csv :
2014-01-01,30
2014-01-02,35
2014-01-03,40
.
.
.


I want to merge into 1 csv file, call merge.csv :

2014-01-01,10,20,30
2014-01-02,15,26,35
2014-01-03,25,46,40


I have tried these:



But it still is not working. How can I do it?

psk psk
Answer

I think that this should do it

$file1 = fopen('file1.csv', 'r');
$file2 = fopen('file2.csv', 'r');
...
$merged = fopen('merged.csv', 'w');

$files = array($file1,$file2,...);
$output=array();

foreach($files as $file){
    while (($line = fgets($file)) !== false) {
        list($index,$value)= explode(',',trim($line));
        $output[$index][]=$value;
    }
}
foreach($output as $key => $values){
    fwrite($merged, $key . ',' . implode(',',$values).PHP_EOL);
}
Comments