fgets
Reads one line from an open file.
Syntax
fgets(resource $stream, ?int $length = null): string|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $stream | resource | A file opened with `fopen()`. |
| $length | ?int | Optional. The maximum number of bytes. |
Return value
string|falseThe line including the line break, or `false` at the end of the file.
Examples
Reading line by line:
<?php
$file = sys_get_temp_dir() . '/ref-fgets.txt';
file_put_contents($file, "first\nsecond\nthird\n");
$handle = fopen($file, 'r');
while (($line = fgets($handle)) !== false) {
echo strlen(rtrim($line)), ' ', rtrim($line), "\n";
}
fclose($handle);Output:
5 first
6 second
5 thirdNotes
This is how large files are read: only one line is in memory at a time. Remove the trailing line break with rtrim().
See also
Related recipes
In the tutorial
- Reading and writing files — Working with files in PHP — writing, reading, appending, reading line by line, checking existence and deleting.