Read each line of text of each file in a directory and place into array?


I have a directory with text files in it and new text files getting added each day. Each text file is a school lesson with 4 lines of text. Line 1 is Lesson Number, line 2 is Lesson Title, line 3 is Description, and line 4 is Due Date.

I need, in PHP, to be able to read all current and future text files and place them into an HTML table. 4 columns in a table labeled Lesson Number, Lesson Title, Description, and Due Date. Each text file being 1 table row.

I've made a site to help out some homeschooled students but wanted to add this functionality to the site to help them view all past, present, and future lessons. I know a little PHP but can't wrap my head around it and it seems the more I try the more I'm getting confused. This is a learning experience for me.

I've tried using fopen but can only get it to open a text file and not a whole directory. I was thinking I need to get a directory listing, place that into an array, and use fopen to open each file in the array but I may be way off. Any help to point me in the right direction is greatly appreciated!


You could go two ways with this either go with glob which will scan the directory or the better Directory Iterator <a href="http://php.net/manual/en/class.directoryiterator.php" rel="nofollow">http://php.net/manual/en/class.directoryiterator.php</a> which i would recommend with the glob method is a bit easier so ill go with that.

It depends with you are already storing the previous records or not but either way ill try to get some examples on here.

I have now improved and tested the below code because the other one i wrote was rubbish

<?php /** * @author - Sephedo * @for - Randall @ Stackoverflow * @question - http://stackoverflow.com/questions/18704981/read-each-line-of-text-of-each-file-in-a-directory-and-place-into-array/18705231#18705231 */ $directory = 'lessons/'; // The directory to the lesson text files $linesToReturn = 4; // Set to four for the number of lines in each text file ( for expansion? ) // Find all files in the directory which are .txt files foreach( glob( $directory . "*.txt" ) as $filename ) { // Open the file if( $handle = @fopen( $filename, "r") ) { $x = 0; // Start the line counter // Cycle each line until end or reach the lines to return limit while(! feof( $handle ) or $x < $linesToReturn ) { $line = fgets($handle); // Read the line $lessons[$filename][] = $line; $x++; // Increase the counter } // This lines makes sure that are exactly 4 lines in each lesson if( count( $lessons[$filename] ) != $linesToReturn ) unset( $lessons[$filename] ); } } // creates a blank list if no files or valid files were found. if(! isset( $lessons ) ) $lessons = array(); // The rest of the page just builds a simple table to display each lesson.- echo '

Lesson Plans

'; echo '<table>'; echo '<th>Lesson Number</th><th>Lesson Title</th><th>Description</th><th>Due Date</th>'; foreach( $lessons as $file => $details ) { echo '<tr><td>' . $details[0] . '</td><td>' . $details[1] . '</td><td>' . $details[2] . '</td><td>' . $details[3] . '</td></tr>'; } echo '</table>'; ?>


Your approach is one way of doing it. You could scan the directory for the files you need, and use the file() function to retrieve file contents in an array. I will only post partial code, as getting file names from a directory is obvious (see glob() in other answers).

//got file list from a given directory in an array (array would contain file names). //it is recommanded, that file names to be with full path, or a relative path to the script

$task_array = Array(); foreach ($filelist as $filename) { try { $file_content = file($filename); // we get an array with this function // you could do this the other way, by using fopen() and fread(), but this is easier } catch(Exception $e) { $(file_content = false; } if (($file_content !== false) && (!empty($file_content))) { $task_array[] = $file_content; } }

Your task array will become a two-dimensional array, like this:

Array( [0] -> Array( [0] -> 1 [1] -> 'Lesson Title' [2] -> 'Lesson Description here' [3] -> '2013-09-25' ) [1] -> Array( [0] -> 2 [1] -> 'Lesson Title 2' [2] -> 'Lesson 2 Description here' [3] -> '2013-09-25' ) )

Then, when you have this array, you could use foreach again, to display it in HTML.

However, if you would want to do this the <em>right</em> way, you should use a database, for example MySQL.


This is how I would traverse a directory and read files:

$dir = "/YOUR_DIRECTORY_PATH/*"; foreach(glob($dir) as $file) { //load each file in the directory $fileHandle = fopen($file, "r"); while (!feof($fileHandle)) { // load each line $line = fgets($fileHandle); echo $line . '<br />'; } fclose($fileHandle); }


  • Saving a dictionary into an .XLSX
  • Using glob() to display images from a directory while echo'ing a unique first image
  • BBC micro:bit - Radio string transfer random carriage returns
  • java.lang.NullPointerException: No FileItemFactory has been set
  • check if numbers have the same sign
  • Sorting a HashMap, while keeping duplicates
  • Does the MySQL IN clause execute the subquery multiple times?
  • Simplify where clause with repeated associated type restrictions
  • Motorola barcode scanner SDK events C#
  • Compress a file with GZipStream while maintaining its meta-data
  • How do I retrieve the user information of a user authenticated with Apache's mod_ldap?
  • How can I include If-None-Match header in HttpRequestMessage
  • Spring: No transaction manager has been configured
  • Suppressing passwd when calling sqlplus from shell script
  • List images(01.png) and descriptions(01.txt) from directory
  • Security issues with PHP's Readfile method
  • Web.config system.webserver errors
  • Tamper-proof configuration files in .NET?
  • Parse a date string in a specific locale (not timezone!)
  • PostgreSQL Query without WHERE only ORDER BY and LIMIT doesn't use index
  • Checking free space on FTP server
  • Change Inet root folder for iis 7
  • FB SDK and cURL: Unknown SSL protocol error in connection to graph.facebook.com:443
  • Display issues when we change from one jquery mobile page to another in firefox
  • Why ng-show works with ng-repeat but ng-if doesn't? [duplicate]
  • Get object from AWS S3 as a stream
  • Cross-Platform Protobuf Serialization
  • Validaiting emails with Net.Mail MailAddress
  • Updated Ionic CLI but shows previous version (Windows)
  • Javascript + PHP Encryption with pidCrypt
  • Upload files with Ajax and Jquery
  • Do I've to free mysql result after storing it?
  • WOWZA + RTMP + HTML5 Playback?
  • bootstrap to use multiple ng-app
  • How to get icons for entities from eclipse?
  • A cron job substitute?
  • json Serialization in asp
  • Turn off referential integrity in Derby? is it possible?
  • How does Linux kernel interrupt the application?
  • JaxB to read class hierarchy