Read Text File Line By Line With PHP

In the following article, we will take a different route to an earlier technique of reading text files with PHP. Rather, we will read a text file line by line with PHP, printing out each line as we loop through the contents.

To read the demo text file line by line we will use the SplFileObject class which, is much nicer and cleaner to use. This class totally revitalizes file reading in PHP in an object-oriented style. It can be used to read files as well as other common functions like writing to files.

For the purpose of the tutorial, this is the data that is stored in the text file which will be read line by line with code.

65
55
23
45
11
22
35
22
44
568
594
33
444
423
983
876
563
634

Let’s put the SplFileObject class into action.

PHP

$myFile = new SplFileObject("data.txt");

while (!$myFile->eof()) {
    echo $myFile->fgets() . PHP_EOL;
}
  • First, we call to the object’s class, passing in the text file path, which in this case is data.txt
  • Second, we use the object method of eof() to produce a boolean loop, this will loop over the data until the end of file is reached.
  • Third, we use another method from the object which is fgets() which reads each line from the file as the loop progresses.

Output

65
55
23
45
11
22
35
22
44
568
594
33
444
423
983
876
563
634

And that is it! If you want to know more about the SplFileObject class then you can head over to the documentation here.

 

Leave a Reply