Using PHP fgets() to Read Files Line by Line
PHP's fgets() function reads a line from an opened file or stream, optionally limiting the number of bytes, and can be used for text and binary files; the article explains its syntax, examples for line-by-line reading, length control, binary handling, and error checking.
PHP fgets() Function Overview
fgets() reads a line from an opened file resource or a filename, optionally limiting the maximum number of bytes per read.
<code>fgets(file,length)</code>The file parameter is a file handle, and length is optional; if omitted, PHP reads until a newline or EOF.
1. Reading a line from a file
Typical usage opens a file with fopen() , then loops until feof() while calling fgets() to retrieve each line.
<code>$file = fopen("data.txt", "r");
while (!feof($file)) {
$line = fgets($file);
echo $line;
}
fclose($file);
</code>2. Specifying maximum bytes per read
Providing the optional length argument limits the number of bytes returned; for example, setting it to 1024 reads up to 1024 bytes per call.
<code>$file = fopen("data.txt", "r");
while (!feof($file)) {
$line = fgets($file, 1024);
echo $line;
}
fclose($file);
</code>3. Reading binary files
When reading binary data, open the file in binary mode (e.g., "rb" ) and use fgets() to obtain each line, remembering that binary streams may contain newline characters.
<code>$file = fopen("image.jpg", "rb");
while (!feof($file)) {
$data = fgets($file);
// process $data
}
fclose($file);
</code>4. Error handling
Check the result of fopen() before reading; if the file cannot be opened, fgets() will not be called and an error message can be displayed.
<code>$file = fopen("data.txt", "r");
if ($file) {
while (!feof($file)) {
$line = fgets($file);
// process $line
}
fclose($file);
} else {
echo "Failed to open file";
}
</code>Summary
The fgets() function is a versatile tool for reading text or binary files line by line in PHP, offering optional byte limits and straightforward error handling, which helps improve file‑processing efficiency and reliability.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.