fgets() is the most commonly used function to read a row of data. Its definition is as follows:
fgets(resource $handle, ?int $length = null): string|false
$handle is an open file pointer (as obtained with fopen() ).
$length is the optional maximum read length (including line breaks). If not specified, fgets() will be read until the end of the line ( \n ) or the end of the file.
Automatically ends with a newline character ( \n ).
Contains newlines in the returned string.
Suitable for reading "standard line format".
Unable to customize line ending characters.
$handle = fopen("https://gitbox.net/data.txt", "r");
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
stream_get_line() is a more underlying and flexible reading function, defined as follows:
stream_get_line(resource $handle, int $length, string $ending = ""): string|false
$length is the maximum number of bytes to be read.
$ending is a custom line ending character (optional).
The ending character itself is not returned.
Allow custom line ending characters (such as "\r\n" commonly used in HTTP headers).
Not suitable for reading binary data blocks containing line breaks.
The return content does not include line ending characters, so it is more suitable for scenarios where data structures are precisely controlled.
$handle = fopen("https://gitbox.net/api/stream", "r");
while (($line = stream_get_line($handle, 1024, "\r\n")) !== false) {
echo $line . PHP_EOL;
}
fclose($handle);
characteristic | fgets() | stream_get_line() |
---|---|---|
Whether to include line breaks | yes | no |
Can you customize the line ending character? | no | yes |
performance | generally | Better (especially in network flow) |
flexibility | Low | high |
Application scenarios | Local text file reading | Network flow, HTTP header parsing, custom protocol flow |
Read local log files or configuration files.
Quickly read text data organized by row.
When writing scripts to process standard input or file input.
Read segmented data in network protocols such as HTTP or SMTP.
Controls row read behavior (excluding ending symbols).
Build your own parser (such as custom protocols, stream data cut based on line ending characters).