CODING ACADEMY

View Original

How to Read a Text File Using PHP

In this lesson I will show you how to read the contents of a text file using PHP.

STEP 1

The first step is to create a text file with some lines of text or ensure you have one on your server. For this example I will just assume you have a robots.txt file (most servers do) and we shall use that.

STEP 2

Create a PHP file and call it something suitable e.g. readTextFile.php

We will place the code which will read the robots.txt file in here.

STEP 3

We start with our opening PHP tag and the the following code:

See this content in the original post

Line 3: we open the robots.txt file using the fopen function. The 'r' at the end means that we want to open the file in read only mode. This is then assigned to the variable $fileContents.

Line 5: we echo out $fileContents

STEP 4

Run the script and see what happens.

Were you expecting to see the contents of the robots.txt file?

What you should see instead is something like $resource id #4

This is not the contents of the robots.txt file but simply a pointer to the file.

STEP 5

To retrieve the contents we can set up a WHILE loop and then echo out each line of the file.

See this content in the original post

Line 5: we set up the WHILE loop. The feof means file end of file. Notice that we have the not operator (!). So what we are saying is: "while we have not reached the end of the file".

Line 6: we use the fgets function to retrieve the next line and echo it out.

Line 9: finally, we close the connection

STEP 6

It would be wise to wrap the whole thing in a conditional statement to check that the file can be opened. If not, then we can present an error message.

See this content in the original post