How to get number of lines with SplFileObject?

Richard Knop picture Richard Knop · Dec 1, 2011 · Viewed 10.9k times · Source
$file = new SplFileObject('/path/to/file.txt');

How can I find the number of lines in a file with SplFileObject?

Answer

Николай Конев picture Николай Конев · Oct 25, 2012

iterator_count and line-by-line iterating using next() is broken in my php version 5.3.7 under Ubuntu.

Also seems broken fseek([any offset], SEEK_END) method. key() returns 0.

Iterate over large files using seek($lineCount) is too slow.

Simpliest 5.3.7-verified way is

// force to seek to last line, won't raise error
$file->seek($file->getSize());
$linesTotal = $file->key();

Counting 30000 lines requires now 0.00002 secs and costs about 20 kb of memory.

Iterations method takes about 3 seconds.