🎓 A1Learner
🔍
0 of 38 lessons completed

Reading Files

Reading files is the act of loading text from a file into a program. PHP offers a whole-file read, a read into an array of lines and a one-line-at-a-time read.

A whole file in one string

The setup line writes a short poem file. file_get_contents then loads the whole file and echo prints both lines.

<?php
file_put_contents("poem.txt", "Roses are red\nViolets are blue\n");
echo file_get_contents("poem.txt");

Lines as an array

The file function returns one array entry per line. The count prints first, and the first two entries print with no added newline because each entry keeps its own.

<?php
file_put_contents("names.txt", "Ana\nMina\nOmar\n");
$lines = file("names.txt");
echo count($lines), "\n";
echo $lines[0];
echo $lines[1];

One line at a time with fgets

fopen opens the file for reading and fgets reads one line per round. The loop stops when feof reports the end, and each printed line carries a number.

<?php
file_put_contents("steps.txt", "Wake\nEat\nSleep\n");
$handle = fopen("steps.txt", "r");
$number = 1;
while (!feof($handle)) {
  $line = fgets($handle);
  if ($line !== false) {
    echo $number . ". " . $line;
    $number++;
  }
}

Example

<?php
file_put_contents("scores.txt", "10\n20\n30\n");
$lines = file("scores.txt");
$total = 0;
foreach ($lines as $line) {
  $total += (int) $line;
}
echo "Total: " . $total . "\n";

Key points

  • file_get_contents returns the whole content of a file as one string.
  • The file function returns the lines of a file as an array.
  • Each line from the file function keeps its ending newline.
  • fopen opens a file and hands back a handle that stands for the open file.
  • fgets reads one line from an open file.
  • feof reports whether the end of an open file has been reached.

In this example, the setup line writes three scores to a file. The file function reads the scores back as an array of lines. The loop casts each line to a number and adds it to the total, which prints as 60.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which function returns the lines of a file as an array?