How to Merge CSV Files in PHP, Line by Line

2019-09-21 19:35发布

问题:

I am trying to merge several CSV files together in PHP. I already have them merged as whole files using PHP thanks to the thread here (Combining 2 CSV files), however I am looking to merge the files together by individual line.

I would like to read line 1 from CSV 1, line 1 from CSV 2, and so forth, then proceed to line 2, 3, etc. - Cycling between the files in the array with each loop. I have not worked with parsing files in PHP much, so I'm not sure where to begin to accomplish this.

This is what I am trying to accomplish, in case the above was not clear:

CSV1 - Line 1

CSV2 - Line 1

CSV3 - Line 1

CSV1 - Line 2

CSV2 - Line 2

CSV3 - Line 2

CSV1 - Line 3

CSV2 - Line 3

CSV3 - Line 3

.... And continue to loop until there are no lines left in the CSV files.

回答1:

Try this php code (gets the lines with file()).:

<?php
$csv1 = file('csv1.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$csv2 = file('csv2.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$csv3 = file('csv3.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = max(count($csv1), count($csv2), count($csv3));
$finalcsv = array();
for($i=0; $i<$lines; $i++) {
  if(isset($csv1[$i])) $finalcsv[] = $csv1[$i];
  if(isset($csv2[$i])) $finalcsv[] = $csv2[$i];
  if(isset($csv3[$i])) $finalcsv[] = $csv3[$i];
}

file_put_contents('final_data.csv', implode(PHP_EOL, $finalcsv));


标签: php parsing csv