Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of lines with SplFileObject?

Tags:

php

spl

$file = new SplFileObject('/path/to/file.txt');

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

like image 296
Richard Knop Avatar asked Dec 01 '11 14:12

Richard Knop


3 Answers

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.

like image 65
Николай Конев Avatar answered Nov 11 '22 04:11

Николай Конев


I agree with Николай Конев on using seek function is much faster than going through the entire file line by line, but as Twisted1919 said using the file size to seek the last line is confusing so my suggestion is use PHP_INT_MAX instead of the file size:

// force to seek to last line, won't raise error
$file->seek(PHP_INT_MAX);
$linesTotal = $file->key();
like image 18
emont01 Avatar answered Nov 11 '22 03:11

emont01


The SplFileObject offers an itertor, one iteration per line:

$numberOfLines = iterator_count($file);

The function iterator_count is your friend here, doing the traversal for you and returning the number of iterations.

You can make use of the file object's SKIP_EMPTY flag to not count empty lines in that file.

like image 6
hakre Avatar answered Nov 11 '22 03:11

hakre