How to read a file in PHP

In this tutorial we will learn how to read from a textfile in PHP. Just like in the article How to create a file in PHP (which I encourage you to read first since this tutorial is based on it) I will spit out the code first and explain after:

<?php
  $fp = fopen("carrots.txt", 'r') or die("Something went wrong, could not open the file");
  $line = fgets($fp);
  fclose($fp);
  echo $line;
?>

In the second line we declare a variable, fp, that holds the returned value of the function fopen(). We satisfy fopen() by passing it two parameters, the file we want to manipulate and how we want to manipulate the file. This time we want to read the file, so the second parameter is set to r for read.

The file to be read in this example have the name 'carrots.txt', with the text 'I am eating carrots'. We read and store that text in the string $line in the next statement:

$line = fgets($fp);

The file pointer fp is being passed to fgets, and fgets takes a line at a time from the file being passed to it. The file is then closed and the text from the file is displayed in the two next statements:

fclose($fp);
echo $line;

If the file had more than one line, we could modify the code to get all the lines:

<?php
  $fh = fopen("testfile.txt", 'r') or die("Something went wrong, could not open the file");
  $line = fgets($fh);
  while (!feof($fh)) {
    echo $line . "&lt;br/&gt;";
    $line = fgets($fh);
  }
  fclose($fh);
?>

fgets() first reads a line and put it on our string $line, then the while-loop is checking if there is more to read from the file. It's looking if it has reached end of file with the function feof(). There is more to read, so it will run the loop until this condition is false. That's how we can read a whole textfile with PHP.

 


 

 

Enjoyed this article? Give the teacher an apple.

cookie

1

Author

authors profile photo

Articles with similar tags

Comments