合并2个CSV文件 [英] Combining 2 CSV files

查看:129
本文介绍了合并2个CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to combine two CSV files in PHP. I'm looking for perfect method. Here's my code so far:

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

推荐答案

如果您拥有大型CVS并且不想使用过多的计算机RAM(假设每个CSV为1GB,例如).

I will give you a solution to use if you have big CVSs and you don't want to use much of your machine's RAM (imagine each CSV is 1GB, for example).

<?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个CSV文件,每个文件约500,000行.花了大约5秒钟的时间,并使用了512kb的内存.

I just used this to concat 2 CSV files of ~500,000 lines each. It took around 5seconds and used 512kb of memory.

逻辑:

打开每个文件,读取一行,然后将其写入输出文件.是的,写入每一行可能比写入整个缓冲区要慢,但这可以在不占用机器内存的情况下使用大量文件. 在任何时候,您都是安全的,因为脚本一次只能在线读取然后写入.

Open each file, read one line and then write it to the output file. Yes, it may be slower writing each line rather than writing a whole buffer, but this allows the usage of heavy files while being gentle on the memory of the machine. At any point, you are safe because the script only reads on line at a time and then writes it.

享受!

这篇关于合并2个CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆