PHP has several ways to read a file. They differ in how much they read at a time.
The examples below use a small file. Create it first:
<?php
file_put_contents("fruits.txt", "apple\nbanana\ncherry\n");
echo filesize("fruits.txt") . " bytes";
20 bytes
fgets(): one line at a time
Best for large files, because only one line is in memory.
<?php
file_put_contents("fruits.txt", "apple\nbanana\ncherry\n");
$handle = fopen("fruits.txt", "r");
while (($line = fgets($handle)) !== false) {
echo "Line: " . trim($line) . "\n";
}
fclose($handle);
Line: apple
Line: banana
Line: cherry
fgets() returns false at the end of the file. Compare with !== false, so that a line containing "0" does not stop the loop.
feof(): are we at the end?
<?php
file_put_contents("fruits.txt", "apple\nbanana\n");
$handle = fopen("fruits.txt", "r");
$count = 0;
while (!feof($handle)) {
$line = fgets($handle);
if ($line !== false) {
$count++;
}
}
fclose($handle);
echo $count . " lines";
2 lines
file(): the whole file as an array of lines
<?php
file_put_contents("fruits.txt", "apple\nbanana\n\ncherry\n");
$lines = file("fruits.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
print_r($lines);
Array
(
[0] => apple
[1] => banana
[2] => cherry
)
FILE_IGNORE_NEW_LINES removes the \n at the end of each item. FILE_SKIP_EMPTY_LINES drops blank lines. Use file() only for files that fit easily in memory.
fread(): a number of bytes
<?php
file_put_contents("fruits.txt", "apple\nbanana\n");
$handle = fopen("fruits.txt", "r");
echo fread($handle, 5);
fclose($handle);
apple
To read a big file in pieces, call fread() in a loop with a size such as 8192.
readfile(): send a file to the output
<?php
file_put_contents("fruits.txt", "apple\nbanana\n");
$bytes = readfile("fruits.txt");
echo "($bytes bytes)";
apple
banana
(13 bytes)
readfile() prints the file and returns how many bytes it sent. It is the right tool to send a download without loading it all into memory.
Choosing
| Need | Use |
|---|---|
| Whole small file as a string | file_get_contents() |
| Whole small file as lines | file() |
| Big file, line by line | fopen() + fgets() |
| Big file in chunks | fopen() + fread() |
| Send a file to the browser | readfile() |
Files can be big
fgets(), or use a generator (see Generators).