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

被刻印的时光 ゝ 提交于 2019-12-14 04:23:30

问题


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!


回答1:


You could go two ways with this either go with glob which will scan the directory or the better Directory Iterator http://php.net/manual/en/class.directoryiterator.php 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 '<h1>Lesson Plans</h1>';
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>';

?>



回答2:


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 right way, you should use a database, for example MySQL.




回答3:


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);
}


来源:https://stackoverflow.com/questions/18704981/read-each-line-of-text-of-each-file-in-a-directory-and-place-into-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!