Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

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

share|improve this answer
    
can you write the full ocde for me ? @Niels Tolstrup –  noob Mar 31 '14 at 19:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.