Extract text out of two lines in a file and output them in a table

2

I am trying to make a PHP script for my school. School's web directory has about 100 text files, one text file for each student. Every text file has a two lines like:

stu $id = '12701';
stu $name = 'alex';

I want to echo out this id and name value in a table. But those two line are random. It might be at line number 23 and 24, or sometimes 45 and 46.

Here's my attempt:

$directory = 'lessons/'; // The directory to the lesson text files

$linesToReturn = 50; //  i tired to read top 50 lines , so i can grab from them.

// 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
        }


    }
}

// 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>id & names</h1>';
echo '<table>';
echo '<th>id</th><th>name</th>';

foreach( $lessons as $file => $details )
{
    echo '<tr><td>' . $details[0] . '</td><td>' . $details[1] . '</td> </tr> ';
}

echo '</table>';

But this doesn't work. What am I doing wrong?

noob

Posted 2014-03-31T17:52:24.343

Reputation: 21

Answers

0

Perhaps you could use a regular expression to grep out the id and name, something along the line of: id=nil

id = line.match( /stu\s+\$id\s*=\s*\'(\d+)\';/)[1] unless id

You might also want to store the data in a more convenient data structure e.g.:

students[ id] = name

Niels Tolstrup

Posted 2014-03-31T17:52:24.343

Reputation: 46

can you write the full ocde for me ? @Niels Tolstrup – noob – 2014-03-31T19:16:57.540