Type Here to Get Search Results !

Lesson 15: Reading from a text file

In the previous lesson, we learned how to use PHP to access the server's filesystem. In this lesson, we will use that information to read from an ordinary text file.
Text files can be extremely useful for storing various kinds of data. They are not quite as flexible as real databases, but text files typically don't require as much memory. Moreover, text files are a plain and simple format that works on most systems.

Open the text file

We use the documentationfopen function to open a text file. The syntax is as follows:

fopen(filename, mode)

filename
Name of the file to be opened.
mode
Mode can be set to "r" (reading), "w" (writing) or "a" (appending). In this lesson, we will only read from a file and, therefore, use "r". In the next lesson, we will learn to write and append text to a file.
The examples in this lesson use the text file unitednations.txt. This is a simple list of the Programmes and Funds of the United Nations and their domains. You can either download the file, or you can create your own file and test the examples with it.

First, let's try to open unitednations.txt:



Example 1: Read a line from the text file

With the function documentationfgets, we can read a line from the text file. This method reads until the first line break (but not including the line break).


show example 

Example 2: Read all lines from the text file 


show example 

In the example, we loop through all the lines and use the function documentationfeof (for end-of-file) to check if you are at the end of the file. If this is not the case ("!" - see lesson 6), the line is written.

Instead of looping through all the lines, we could have achieved the same result with the function documentationfread. If you work with very large text files with thousands of lines, be aware that the documentationfread function uses more resources than the documentationfgets function. For smaller files, it makes very little difference.

Example 3: A simple link directory

As mentioned at the beginning of this lesson, text files can be excellent for data storage. This is illustrated in the next example where we create a simple link directory from the contents of the text file unitednations.txt.

The file is systematically written with the name of the program, then a comma, and then the domain. As you can probably imagine, more information could easily be stored in this comma-separated data file.

To get the information in each line, we use an array. See Lesson 8 for more information on arrays.


show example 

Quite handy, right? In principle, you could now just expand the text file with hundreds of links or perhaps expand your directory to also include address information.

In the next lesson, we will look at how to write to a text file.

Post a Comment

0 Comments