I am Trying to Merge Multiple CSV Files but unable to do that. Please have a look my code I dont know whats wrong with my code. csvfiles is a directory which contains multiple same format Files.
My Code
$csvdir = "./csvfiles/";
$result = fopen('./csvfiles/merge.csv', 'w');
$test="";
if (is_dir($csvdir)) {
if ($handle = opendir($csvdir)){
while (($file = readdir($handle)) !== false) {
if (substr($file, -4) === ".csv") {
$csvcontent = file_get_contents($file);
fwrite($result, $csvcontent);
}
}
closedir($handle);
}
}
fclose($result);
Some observations:
At some point opendir($csvdir)
will also include your merge.csv
file. You want to avoid that. Keep it seperate.
Keep file operations at minimum. For every .csv file in your loop you write to your merge.csv
. Instead, collect the data to write in your loop and write only once.
You're getting the wrong file contents in file_get_contents($file);
. $file
will only contain the filename, not the complete path.
$test
is never used.
Here's working code:
<?php
$csvdir = "./csvfiles/";
$csvcontent = '';
if (is_dir($csvdir)) {
if ($handle = opendir($csvdir)) {
while (($file = readdir($handle)) !== false) {
if (substr($file, -4) === ".csv") {
$csvcontent .= file_get_contents($csvdir . $file);
}
}
closedir($handle);
}
}
$result = fopen('./merge.csv', 'w');
fwrite($result, $csvcontent);
fclose($result);