The fgets Function
The fgets
function reads a line from a file. Its first parameter is a file pointer, which must be previously opened with the fopen
function. The second optional parameter allows you to specify the maximum length of the line to be read. The function stops reading upon reaching the end of the line, the end of the file, or the specified length.
Syntax
fgets(resource $handle, int $length = ?): string|false
Example
Read the first line from a file:
<?php
$file = fopen('test.txt', 'r');
echo fgets($file);
fclose($file);
?>
Example
Reading a file line by line in a loop:
<?php
$file = fopen('test.txt', 'r');
while ($line = fgets($file)) {
echo $line;
}
fclose($file);
?>
Example
Reading a line with a length limit:
<?php
$file = fopen('test.txt', 'r');
echo fgets($file, 4);
fclose($file);
?>