合并2个CSV文件

时间:2011-03-24 10:28:45

标签: php

我正在尝试在PHP中合并两个CSV文件。我正在寻找完美的方法。到目前为止,这是我的代码:

$one = fopen('data5.csv', 'r');
$two = fopen('userdata.csv', 'r');

$final = fopen('final_data.csv', 'a');

$temp1 = fread($one, filesize("data5.csv"));
$temp2 = fread($two, filesize("userdata.csv"));

fwrite($final, $temp1); 
fwrite($final, $temp2);

4 个答案:

答案 0 :(得分:22)

如果您有大型CVS并且您不想使用机器的大部分RAM(例如,假设每个CSV为1GB),我会给您一个解决方案。

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

有趣的事实:

我只是用它来连接2个大约500,000行的CSV文件。花了大约5秒钟,使用了512kb的内存。

<强>逻辑:

打开每个文件,读取一行,然后将其写入输出文件。是的,写入每一行可能比写一个整个缓冲区要慢,但这样可以使用繁重的文件,同时对机器的内存保持温和。 在任何时候,您都是安全的,因为脚本一次只能在线读取然后写入。

享受!

答案 1 :(得分:2)

怎么样......

file_put_contents('final_data.csv',
    file_get_contents('data5.csv') .
    file_get_contents('userdata.csv')
);

请注意,这会将整个文件加载到PHP内存中。所以,如果它们很大,你可能会遇到memory_limit问题。

答案 2 :(得分:0)

如果你想只连接这两个文件,你可以通过执行shell脚本轻松地做到这一点,假设你像os一样使用unix:

exec("cat data5.csv > final_data.csv && cat userdata.csv >> final_data.csv");

答案 3 :(得分:0)

ob_start();  
$dir1 = "csv/2014-01/";  
$dir = $_REQUEST['folder_name'];  
$totalfiles =  count(glob($dir."/*",GLOB_BRACE));  
echo "Total files in folder = ".$totalfiles;  
if ($opend = opendir($dir)){  
    $i =0;  $final_array_export= array();  
    $fil_csv =end(explode('/',$dir));  
        $file_name = 'download/'.$fil_csv.'.csv';
        $file_cre = fopen($file_name,"w");
        $headers = array("header1","header2");
        fputcsv($file_cre,$headers);
        while (($file = readdir($opend)) !== false){
            $filename = $dir.'/'.$file;
            $files = fopen($filename,"r");
            if($files){
                $fullarray = fgetcsv($files);
                $head=array();
                if(count($fullarray) >0){    
                    foreach($fullarray as $headers){    
                        $head[] = $headers;  
                    }
                }

                while($data =  fgetcsv($files,0,",")){
                    if(count($data) >0 && count($head) >0){
                        $array_combine = array_combine($head,$data);
                    }

                    fputcsv($file_cre,$array_combine);  
                }
            }
        }

        fclose($file_cre);
        header("Content-Type: application/force-download");
        header("Content-type: application/csv");
        header('Content-Description: File Download');
        header('Content-Disposition: attachment; filename=' . $file_name);
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-length: ' . filesize($file_name));
        ob_clean();
        flush();
        readfile($file_name);
    }