In PHP, handling file reading and writing is a common task. The fgets() function is an important function designed specifically to read file content line by line. This article will explain how to use fgets() in depth and provide sample code to help you better understand and apply this function.
The fgets() function is defined as follows:
string fgets(resource $handle [, int $length])
Here, $handle is a resource pointing to an already opened file, and $length is an optional parameter specifying the maximum number of bytes to read each time. If omitted, it reads the entire line, including the newline character at the end.
<?php // Open the file $file = fopen("example.txt", "r"); <p>// Read one line<br> $line = fgets($file);</p> <p>// Output the line<br> echo $line;</p> <p>// Close the file<br> fclose($file);<br> ?>
In this example, fopen() opens the file example.txt. The fgets() function reads the first line, outputs it, and then the file is closed. Note that fgets() reads one line at a time.
// Output the line
echo $line;
}
// Close the file
fclose($file);
?>
This example uses feof() to check for the end of the file and reads the file line by line in a loop until all lines are read.
The fgets() function is an efficient way in PHP to read files line by line, especially useful when handling large files. Mastering this function allows developers to handle file operations more flexibly, improving code readability and maintainability.