PHP:
Reading a text file

How to:

Using file_get_contents:

$content = file_get_contents("example.txt");
echo $content;

Sample Output:

Hello, World!
This is content from the text file.

Using fopen and fgets:

$handle = fopen("example.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        echo $line;
    }
    fclose($handle);
}

Sample Output:

Hello, World!
This is content from the text file.

Writing to a file with file_put_contents:

$newContent = "Adding new text.";
file_put_contents("example.txt", $newContent);

Deep Dive

Reading text files is as old as programming itself. Before databases, config files, and user data often lived in simple text files. Alternatives like XML and JSON files are structured, easier to parse, and well-suited for complex data.

In PHP, file_get_contents and file() are quick for reading; the former gets everything in one string, and the latter in an array. fopen coupled with fgets or fread gives you more control, particularly for large files, as you read it line-by-line or in chunks.

Some nuances: fopen requires appropriate permissions, or it’ll fail; handling its errors is a best practice. When using file_put_contents, be aware it overwrites the file by default; use the FILE_APPEND flag to add content instead.

See Also