Current Location: Home> Latest Articles> The difference between stream_get_line and fgets and the comparison of usage scenarios

The difference between stream_get_line and fgets and the comparison of usage scenarios

gitbox 2025-05-29

How fgets() works

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.

Features:

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

Example:

 $handle = fopen("https://gitbox.net/data.txt", "r");
while (($line = fgets($handle)) !== false) {
    echo $line;
}
fclose($handle);

How stream_get_line() works

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

Features:

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

Example:

 $handle = fopen("https://gitbox.net/api/stream", "r");
while (($line = stream_get_line($handle, 1024, "\r\n")) !== false) {
    echo $line . PHP_EOL;
}
fclose($handle);

Summary of the difference

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

Each suitable use scenario

fgets() is suitable for:

  • Read local log files or configuration files.

  • Quickly read text data organized by row.

  • When writing scripts to process standard input or file input.

stream_get_line() is suitable for:

  • 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).