← Tous les articles

PHP: import a large CSV file without running out of memory, using generators

A catalogue import that works with 2,000 rows and dies at 200,000 almost always comes down to file() or one giant array. Streaming rows, generators and batched transactions, plus the traps in CSV files exported from Excel.

PHP: import a large CSV file without running out of memory, using generators

Key points

  • Never load the whole file: stream it row by row with fgetcsv() and a generator.
  • Insert in batches of a few hundred rows inside a transaction, reusing one prepared statement.
  • Expect Excel’s BOM, comma decimals and rows with the wrong number of columns.

We hear this one regularly: “the catalogue import used to work, but since the supplier started sending the full file the page spins and then errors out”. The code nearly always starts with file() or array_map('str_getcsv', ...), pulling the entire file into memory, followed by a loop that builds a second array just as large. Raising memory_limit only postpones the crash to the next, bigger file. The real fix is to never hold more than a handful of rows at once.

Stream rows with a generator

A generator is a function that uses yield: it hands back a value, pauses, and resumes on the next loop iteration. The calling code is a plain foreach, yet only one row of the file lives in memory at any moment.

function readCsv(string $path, string $separator = ';'): Generator
{
    $handle = fopen($path, 'rb');
    if ($handle === false) {
        throw new RuntimeException("Cannot open $path");
    }

    try {
        $header = fgetcsv($handle, null, $separator, '"', '');
        // Excel's "CSV UTF-8" adds a BOM to the first column name
        $header[0] = preg_replace('/^xEFxBBxBF/', '', $header[0]);

        $line = 1;
        while (($row = fgetcsv($handle, null, $separator, '"', '')) !== false) {
            $line++;
            if ($row === [null]) {
                continue; // empty line
            }
            if (count($row) !== count($header)) {
                throw new UnexpectedValueException("Line $line: wrong number of columns");
            }
            yield $line => array_combine($header, $row);
        }
    } finally {
        fclose($handle);
    }
}

A few details matter. The finally block closes the file even if the import stops on an exception. Passing an empty escape character to fgetcsv() turns off PHP’s legacy escaping, matches standard CSV, and avoids the deprecation notice in recent PHP versions. And yielding the line number as the key gives you error messages a client can actually act on.

Write to the database in batches

One transaction per row is slow; one transaction for 200,000 rows locks the table for far too long. What works well on our projects is batches of a few hundred rows with a statement prepared once.

function batches(iterable $rows, int $size): Generator
{
    $batch = [];
    foreach ($rows as $row) {
        $batch[] = $row;
        if (count($batch) === $size) {
            yield $batch;
            $batch = [];
        }
    }
    if ($batch !== []) {
        yield $batch;
    }
}

$stmt = $pdo->prepare(
    'INSERT INTO products (sku, name, price_cents) VALUES (?, ?, ?)
     ON DUPLICATE KEY UPDATE name = VALUES(name), price_cents = VALUES(price_cents)'
);

foreach (batches(readCsv($file), 500) as $batch) {
    $pdo->beginTransaction();
    foreach ($batch as $row) {
        $price = (int) round((float) str_replace(',', '.', $row['price']) * 100);
        $stmt->execute([trim($row['sku']), trim($row['name']), $price]);
    }
    $pdo->commit();
}

echo round(memory_get_peak_usage() / 1048576, 1), " MB peakn";

The second generator groups rows without ever materialising the full file. On MySQL 8.0.20 and later, the row-alias syntax supersedes VALUES() in ON DUPLICATE KEY UPDATE, though the old form still works; MariaDB only supports VALUES(). Printing peak memory at the end is a good habit: it should stay flat whatever the file size.

What real-world files throw at you

The BOM, first. A file saved as “CSV UTF-8” from Excel starts with three invisible bytes, so without the cleanup your sku column is really named “xEFxBBxBFsku” and $row['sku'] raises a warning. It cost us an hour the first time.

Then numbers: depending on Excel’s language, prices arrive as “12,90” or “12.90”, and columns are separated by semicolons or commas. Make the separator configurable and normalise decimals. Finally, run imports from the command line or a scheduled job rather than an HTTP request; the web server’s timeout will eventually cut the job off halfway through.

FAQ

Do generators make the import faster?

Not by themselves: they cut memory use. Speed comes mostly from batched transactions and reusing the prepared statement.

What about WordPress?

The same generator works as is. For the write side, a custom WP-CLI command is a better fit than an admin page, precisely to stay clear of request timeouts.

Are your data imports slowing down or crashing on large files? We build robust imports for WordPress and SaaS applications, with error recovery and readable reports.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →