Current Location: Home> Latest Articles> PHP fgets() Function Explained: Practical Tips for Reading Files Line by Line

PHP fgets() Function Explained: Practical Tips for Reading Files Line by Line

M66 2025-06-15

Introduction to PHP fgets() Function: Practical Method for Reading Files Line by Line

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.

Basic Syntax of fgets() 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.

Example of Reading a Single Line Using fgets()

<?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.

Example of Reading the Entire File Line by Line

// 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.

Conclusion

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.