How to get row count with SplFileObject?

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

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

+5
source share
4 answers

Why not just use file handlers and use this question ? Its simple, fast and very efficient.

If you absolutely must use spl, you can do it like this

$file = new SplFileObject("/path/to/file.txt");
$i = 0;
while (!$file->eof()) {
    $i++;
    $file->next();
}
print "file has " . $i . " lines"; 
+4
source

iterator_countand phasing using is next()broken in my php version 5.3.7 under Ubuntu.

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

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

5.3.7-

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

30000 0,00002 20 .

3 .

+34

seek function , , Twisted1919 , , PHP_INT_MAX :

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

SplFileObject , :

$numberOfLines = iterator_count($file);

iterator_count , .

SKIP_EMPTY flag, .

+3

All Articles