Count Millions of CSV Rows Efficiently in PHP with SplFileObject
Learn a fast, memory‑efficient PHP technique that uses SplFileObject to count rows in massive CSV files without loading the entire file into memory, suitable for datasets with hundreds of thousands or millions of lines.
This article presents a concise, high‑performance method for counting the number of rows in a CSV file using PHP, even when the file contains millions of lines.
Why use SplFileObject?
SplFileObject reads a file line‑by‑line without loading the whole file into memory, avoiding the huge memory consumption that functions like file_get_contents would cause on large CSVs.
Step‑by‑step implementation
Open the CSV file with SplFileObject:
$file = new SplFileObject('transactions.csv', 'r');Seek to the maximum possible line index, which moves the internal pointer to the end of the file: $file->seek(PHP_INT_MAX); Retrieve the current zero‑based line number with key() and add one to obtain the total row count:
$rows = $file->key() + 1; // total number of rowsIf the CSV includes a header row and you prefer not to count it, simply omit the "+ 1" adjustment.
Result
For a file named transactions.csv that contains 12 lines, the variable $rows will hold the value 12.
This approach provides a short, memory‑efficient way to read and count rows in a CSV file using PHP.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
