To open and read a file line by line:
$file = fopen( "/path/to/file.txt", "r" );
$index=0;
while ((( $line = fgets( $file )) !== false) && ( $index++ < 5 )) {
echo $line;
}
fclose( $file );
Here, I am initializing a variable index
to 0.
In the while loop, we will use fgets
to read the next line of the file, and assign it to the variable line
. We will also check that the value of index
is less then 5, our desired line count, in addition to incrementing the value of the index, after we have read the line.
Once the value of index has reached > 5, the loop will exit, and the file stream will be closed.
The advantage of using fopen
and fgets
over something like file
, is that the latter will load the entire contents of the file into memory - even if you do not plan on using the whole thing.
With a multi line file, the above code will print out the first five lines.
This is a multi line