Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to read a file line by line

Short answer

A small file is easiest to read into an array of lines:

<?php
 
$file = sys_get_temp_dir() . '/recipe-lines.txt';
file_put_contents($file, "first\nsecond\nthird\n");
 
foreach (file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $number => $line) {
    echo $number + 1, ': ', $line, "\n";
}

Output:

1: first
2: second
3: third

A large file

fgets() reads one line at a time and does not load the whole file into memory:

<?php
 
$file = sys_get_temp_dir() . '/recipe-lines.txt';
file_put_contents($file, "first\nsecond\nthird\n");
 
$handle = fopen($file, 'r');
$count = 0;
 
while (($line = fgets($handle)) !== false) {
    $count++;
}
 
fclose($handle);
 
echo $count;

Output:

3

A generator

Reading is conveniently hidden in a generator, so the file is looped over like an array:

<?php
 
function lines(string $file): Generator
{
    $handle = fopen($file, 'r');
 
    while (($line = fgets($handle)) !== false) {
        yield rtrim($line, "\r\n");
    }
 
    fclose($handle);
}
 
$file = sys_get_temp_dir() . '/recipe-lines.txt';
file_put_contents($file, "first\nsecond\nthird\n");
 
foreach (lines($file) as $line) {
    echo strtoupper($line), ' ';
}

Output:

FIRST SECOND THIRD

Functions used in this recipe

  • fgets — Reads one line from an open file.
  • fopen — Opens a file for reading or writing piece by piece.
  • file — Reads a file into an array of lines.

Thanks for reading!

Donate to the site — we work hard for you.