Split large CSV files in to multiple CSV files using PHP

By using this PHP code snippet you can split large CSV files in to multiple CSV files.


									<?php

function SplitCSV($csvPath, $outputPath, $splitSize, $keepHeaders = true) {
	$currentRow = 0;
	$currentFile = 1;
	
	$fh = fopen($csvPath, 'r');
	if ($keepHeaders) $headers = fgetcsv($fh);
	while (!feof($fh)) {
		if ($currentRow % $splitSize == 0) {
			if ($currentRow > 0) fclose($outputFile);
			$outputFile = fopen($outputPath . "_" . $currentFile++ . ".csv", 'w');
			if ($keepHeaders) fputcsv($outputFile, $headers);
		}
		if ($row = fgetcsv($fh)) fputcsv($outputFile, $row);
		++$currentRow;
	}
	fclose($fh);
}

// Example:
SplitCSV("sample.csv", "out/sample", 3); // Output: out/sample_1.csv, out/sample_2.csv, ...

?>
								

wise_man

Hope for good, prepare for everything.

Comments (0)

No Comments Yet.