使用PHP水平合并CSV文件

时间:2015-12-10 14:09:08

标签: php csv

您好,我只是想知道这是否可以使用PHP,所以这是场景...

我有一个CSV文件示例' first.csv':

"Name","Age","Job"
"Peter Algarve","17","Mechanic"
"Will Smith","50","Actor"

然后我有了这个CSV' second.csv':

"Origin","Eye Color","Birthday"
"Jamaica","Red","17-8-1967"
"USA","Brown","2-8-1969"

现在我要做的是将第二个CSV数据添加到第一个CSV行的末尾,如下所示:

"Name","Age","Job","Origin","Eye Color","Birthday"
"Peter Algarve","17","Mechanic","Jamaica","Red","17-8-1967"
"Will Smith","50","Actor","USA","Brown","2-8-1969"

注意我还需要添加一个逗号来分隔新列,有没有办法在PHP中完成这个?

2 个答案:

答案 0 :(得分:1)

使用file()

将每个文件读入数组
$first = file('firstFile.csv');
$second = file ('secondFile.csv');

迭代数组并构造一个新数组,连接两行,用逗号分隔 并使用trim()删除我们可能在此过程中拾取的任何新行字符。

foreach ($first as $i=>$row){
    $result[$i] = trim($row) . "," . trim($second[$i]);
}

将结果数组写入新的csv文件

$fp = fopen('result.csv', 'w');

foreach ($result as $line) {
    fputcsv($fp, $line);
}

fclose($fp);

执行print_r($result)将输出

Array
(
    [0] => "Name","Age","Job","Origin","Eye Color","Birthday"
    [1] => "Peter Algarve","17","Mechanic","Jamaica","Red","17-8-1967"
    [2] => "Will Smith","50","Actor","USA","Brown","2-8-1969"
)

答案 1 :(得分:0)

如果要创建合并输出的csv,则无需将所有数据读入内存,只需逐行读取,合并和写入:

$fileOneHandle     = fopen('first.csv', 'r');
$fileTwoHandle     = fopen('second.csv', 'r');
$fileMergedHandle  = fopen('merged.csv', 'w');

while($fileOneLine = fgetcsv($fileOneHandle) && $fileTwoLine = fgetcsv($fileTwoHandle)){
    fputcsv($fileMergedHandle, array_merge($fileOneLine, $fileTwoLine));
}

fclose($fileOneHandle);
fclose($fileTwoHandle);
fclose($fileMergedHandle);