PHP Function Reference

PHP stream_get_line() Function



The PHP stream_get_line() function gets a line from the given stream.

Reading ends when length bytes have been read, when the non-empty string specified by ending is found (which is not included in the return value), or on EOF (whichever comes first).

This function is nearly identical to fgets() except in that it allows end of line delimiters other than the standard \n, \r, and \r\n, and does not return the delimiter itself.

Syntax

stream_get_line(stream, length, ending)

Parameters

stream Required. Specify the valid file stream.
length Required. Specify the maximum number of bytes to read from the stream. Negative values are not supported. Zero (0) means the default socket chunk size, i.e. 8192 bytes.
ending Optional. Specify the string delimiter.

Return Value

Returns a string of up to length bytes read from the file pointed to by stream. If an error occurs, returns false.

Example: Reading specified bytes from a file

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, the file is opened using fopen() function. Then the first 25 bytes from the first line is read. After performing this reading operation, it is closed using fclose() function.

<?php
//open the file in read mode
$fp = fopen("test.txt", "r") or 
         die("Unable to open file!");

//reading first 25 bytes and 
//displaying the read content
echo stream_get_line($fp, 25);

//close the file
fclose($fp);
?>

The output of the above code will be:

This is a test file.
It

Example: Reading first line from a file

To read the first line from a file, the stream_get_line() function can be used with ending parameter as "\n". Consider the example below:

<?php
//open the file in read mode
$fp = fopen("test.txt", "r") or 
         die("Unable to open file!");

//reading first line and 
//displaying the read content
echo stream_get_line($fp, 0, "\n");

//close the file
fclose($fp);
?>

The output of the above code will be:

This is a test file.

Example: Reading a file line by line

By using feof() function in a while loop, a file can be read line by line. Consider the example below:

<?php
//open the file in read mode
$fp = fopen("test.txt", "r") or 
         die("Unable to open file!");

//reading the file line by line
//and displaying the read content
while(!feof($fp)) {
  echo stream_get_line($fp, 0, "\n");
}

//close the file
fclose($fp);
?>

The output of the above code will be:

This is a test file.
It contains dummy content.

❮ PHP Streams Reference