PHP offers many functions for file manipulation. The fgets
function in PHP reads a line from an already open file.
The syntax for the fgets
function is shown below:
fgets(resource $file, int $length = ?): string|false
The fgets
function has two parameters:
file
: This is a required parameter. file
is the name of the file stream that points to an already open file. A line will be returned from this file.length
: This is an optional parameter. The length
parameter specifies the number of bytes to be read from the file.The fgets()
function returns a single line, read from the file.
If the function is unable to return a line due to an error or by coming to the end of the file, it returns false
.
The following code shows how we can use the fgets
function.
<?php$file = fopen("test.txt","r"); // open the file//example without lengthwhile(!feof($file)) //checks if at end of the file{echo fgets($file); //reads one line from the file}// example with lengthwhile(!feof($file)) //checks if at end of the file{echo fgets($file, 12); //reads 12 bytes line from the file}fclose($file); // close the file?>
Free Resources