HOWTO · PHP

How to Read Text Files in PHP

Learn three practical ways to read text files in PHP, with examples and guidance on memory use and line endings.

On this page

PHP offers different ways to read a text file, depending on whether you want to process one line at a time or work with the complete contents. Use fgets() with an open stream for large files or incremental processing. Use file() when an array of lines is convenient, and file_get_contents() with explode() when you need the whole text as a string. The examples below create their own temporary input file so they can be adapted without relying on an existing abc.txt file.

Read a file one line at a time with fgets()

Open a stream with fopen() in read mode, then call fgets() repeatedly. Each call returns the next line, including its line ending when present, or false when the read reaches the end or fails. The optional second argument sets the buffer length, and fgets() reads up to length minus one bytes: with a length of 10, it reads at most 9 bytes. This is a byte count, not a character count, and a long line may therefore be returned across multiple calls. The first argument is the stream handle, not a filename.

Run this example:

<?php
$path = tempnam(sys_get_temp_dir(), 'php-read-');
file_put_contents($path, "Hi\nHow are you\nHave a great day\n");
$handle = fopen($path, 'r');

if ($handle === false) {
    echo "Could not open file\n";
} else {
    $number = 1;
    while (($line = fgets($handle)) !== false) {
        echo $number . ': ' . rtrim($line, "\r\n") . "\n";
        $number++;
    }
    fclose($handle);
}

unlink($path);
?>

This pattern keeps only the current line in your PHP variables, so it is useful when processing a file that is too large to load all at once. Check that fopen() returned a handle before reading, and close a successfully opened stream with fclose(). A false result from fgets() can mean end of file or a read failure; if your application must distinguish them, inspect the stream’s EOF state after the loop and handle the failure accordingly.

Load a file into an array with file()

file() reads the entire file into an array, with one array element per line. This makes iteration simple, but the file and its line strings occupy memory together. It returns false if it cannot read the file, so check the result before passing it to foreach.

<?php
$path = tempnam(sys_get_temp_dir(), 'php-read-');
file_put_contents($path, "Hi\nHow are you\nHave a great day\n");
$lines = file($path);

if ($lines === false) {
    echo "Could not read file\n";
} else {
    foreach ($lines as $index => $line) {
        echo 'Line ' . ($index + 1) . ': ' . rtrim($line, "\r\n") . "\n";
    }
}

unlink($path);
?>

By default, each line keeps its newline characters. You can pass FILE_IGNORE_NEW_LINES as the second argument to remove line endings, or combine it with FILE_SKIP_EMPTY_LINES to omit blank lines. These flags change the returned data: use them only if removing those characters or lines fits the task. The array keys in this example start at zero, so adding one displays human-friendly line numbers.

Read a file as a string with file_get_contents() and split it with explode()

file_get_contents() loads the whole file into one string and returns false on failure. After checking that result, explode() can split the string at a chosen separator. This is convenient when the complete text is needed, but both the string and the resulting array use memory.

<?php
$path = tempnam(sys_get_temp_dir(), 'php-read-');
file_put_contents($path, "Hi\nHow are you\nHave a great day\n");
$contents = file_get_contents($path);

if ($contents === false) {
    echo "Could not read file\n";
} else {
    $lines = explode("\n", $contents);
    foreach ($lines as $line) {
        echo rtrim($line, "\r") . "\n";
    }
}

unlink($path);
?>

Splitting on "\n" handles LF line endings. In CRLF files, a carriage return (\r) remains at the end of each line, which the example removes for display. A file ending with a newline also produces a final empty array element; decide whether to retain or filter it based on what the file format means. Files using other newline conventions need corresponding handling, so do not assume every text source uses LF.

Choose a reading method and handle common pitfalls

Choose fgets() when you can process each line as it arrives or need bounded memory use. Choose file() when the file is modest and an array makes later processing clearer. Choose file_get_contents() with explode() when you need whole-file string operations and can account for the extra memory used by the split array.

For all three approaches, check the function’s return value before using it: failed reads can return false. Use a path that the PHP process can access, and account for permissions and the current working directory when a relative path is involved. Keep newline handling intentional: line-reading functions normally retain line endings, while flags or trimming can remove them; splitting on a literal separator can leave carriage returns or a trailing empty element. These details affect comparisons, displayed text, and parsing, so preserve the original line endings when they carry meaning.