duanpi7578 2017-10-13 05:30
浏览 125
已采纳

合并多个CSV文件

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.

Download Sample CSV 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);
  • 写回答

1条回答 默认 最新

  • douchao5864 2017-10-13 09:24
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?