Backend Development 6 min read

Using PHP fgets() to Read Files Line by Line

This article explains how to use PHP's fgets() function to read files line by line, covering its syntax, parameters, and providing three practical code examples for basic reading, limiting byte length, and processing each line, including handling of file opening and closing.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP fgets() to Read Files Line by Line

In PHP, reading files is a common operation, and the fgets() function helps read data from a file one line at a time. This function is especially useful when handling large text files.

The basic syntax of fgets() is:

string fgets ( resource $handle, int $length );

Parameter Explanation:

$handle : a file resource returned by fopen() .

$length : optional, specifies the maximum number of bytes to read (default 1024 bytes).

Example Code 1: Basic Usage

Assume we have a text file example.txt with the following content:

Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.

We want to read each line and display it on the page:

$handle = fopen("example.txt", "r");

if ($handle) {
    while (($line = fgets($handle)) !== false) {
        echo $line . "
";
    }
    fclose($handle);
} else {
    echo "Unable to open file";
}

This program uses fopen() to open example.txt , then reads each line with fgets() inside a while loop, outputs the line, and finally closes the file with fclose() .

The output of the above code is:

Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.

Example Code 2: Limiting Read Bytes

Sometimes you may only need to read the first few bytes of each line. The second parameter $length of fgets() allows you to limit the number of bytes read. The following example reads only the first 10 bytes of each line:

$handle = fopen("example.txt", "r");

if ($handle) {
    while (($line = fgets($handle, 10)) !== false) {
        echo $line . "
";
    }
    fclose($handle);
} else {
    echo "Unable to open file";
}

The result of this code is:

Lorem ipsu
consectetu
sed do eiu
ut labore

Example Code 3: Processing Each Line

Beyond simply outputting lines, you can process each line further, such as counting characters and storing the results in an array:

$handle = fopen("example.txt", "r");
$result = [];

if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $lineLength = strlen($line);
        $result[] = $lineLength;
    }
    fclose($handle);
} else {
    echo "Unable to open file";
}

print_r($result);

This code uses strlen() to calculate the length of each line, stores the lengths in $result , and then prints the array. The output looks like:

Array
(
    [0] => 28
    [1] => 28
    [2] => 30
    [3] => 24
)

Summary

The fgets() function is a very useful tool for reading data from a file line by line. Its usage is simple, and the basic syntax is easy to understand. You can read each line of a file and further process it, such as outputting to a page or counting characters. By mastering and flexibly applying fgets() , handling large text files becomes much more convenient.

backend developmentphpcode examplesfile handlingfgets
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.