Split Large CSV Files in PHP

Split CSV by parsed records, not by raw lines: a quoted field can legally contain a line break. PHP’s CSV parser reads one logical record at a time, so the process can remain memory-bounded and preserve valid quoting.

Last updated: September 26, 2026.

$input = new SplFileObject('customers.csv', 'r');
$input->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY);
$input->setCsvControl(',', '"', '');

$header = $input->fgetcsv(',', '"', '');
$rowsPerFile = 50000;
$part = 0;
$rowInPart = $rowsPerFile;

foreach ($input as $row) {
    if ($row === false || $row === [null]) continue;
    if ($rowInPart >= $rowsPerFile) {
        $part++;
        $output = new SplFileObject(sprintf('customers-%03d.csv', $part), 'w');
        $output->fputcsv($header, ',', '"', '', "
");
        $rowInPart = 0;
    }
    $output->fputcsv($row, ',', '"', '', "
");
    $rowInPart++;
}

Passing an empty escape character follows standard doubled-quote escaping and avoids relying on the deprecated default behavior in PHP 8.4 and later.

Validate the input contract

Confirm the delimiter, enclosure, encoding, header presence, and line-ending expectations before splitting. If the delimiter is unknown, use the delimiter detection procedure on a representative sample. Convert encoding before parsing when the source contract requires it.

Protect the output directory

Generate filenames yourself in a dedicated non-public directory. Do not concatenate an uploaded filename into a filesystem path. Check disk space, handle write failures, and write to temporary names before renaming completed parts. Record part number, row count, and checksum in a manifest so downstream processing can detect missing or repeated files.

Verify every part

  • The header appears exactly once per part.
  • The sum of data rows equals the accepted input count.
  • Every row has the expected number of fields when the format requires it.
  • Quoted commas, quotes, and embedded newlines round-trip correctly.
  • No empty final part is produced.

The PHP SplFileObject CSV reference describes the delimiter and escape rules. For general iteration and error handling, review reading large CSV files without exhausting memory.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov