Why does this print the last line? (SplFileObject)

845 Views Asked by At
$file1 = new \SplFileObject('some file');
while( !$file1->eof() ){
    $data = $file1->fgets();
    if( !$file1->eof() ){
       echo $data;
    }
}

Doesn't fgets() step to the next line in the file? If so why does the file still pass the second !$file1->eof() statement? This occurs with ->valid() also.

2

There are 2 best solutions below

0
VolkerK On BEST ANSWER

feof/SplFileObject::eof test whether the file handle/stream is at the EOF position.
Your source file has a linebreak after the last data line and fgets() stops right there. But the EOF position is figuratively speaking one position after that last read operation. SO the next fgets() (and subsequently read()) will return 0 bytes and only then the file is at the EOF position and feof() will return true.
In your concrete example (nasdaqlisted.txt) it might be sufficient to just test if $data is ==='' instead of $file1->eof() as there seem to be no other emtpy lines in that file.

0
Oras On

You're overriding $data each time loop runs. Try this: $data .= $file1->fgets();