Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data from text file and displaying it in a table using PHP

I have text files that I would like to read into a website and then display. I use

$sListText = file_get_contents("result - 0001.txt");
echo nl2br($sListText);

which loads it fine with line breaks. I just have no clue how to turn the table data into a table with php.

The text file looks like this:

Prestige Byeenkoms 2014 Dal Josafat Stadion,    10/02/2014

Item: 1 (Dogters - 14) Spiesgooi 500 gm

Pos Naam    Van Span    Uitslag Punt    ASA Rek
1   Marle   Rademan GHBH    35.67   8   879 R
2   Lara    Jordaan GHBH    25.58   5   671 
3   Martine Hartung PG  24.67   4   650 
4   Marlie  Theunissen  PG  23.50   3   622 
5   Rochelle    ROOS    BLRO    21.75   2   578 
6   Mishka  ELLIS   BLRO    21.20   1   564 

The top two lines at the top are the headings. The data underneath must form a table with no border.

Can anyone please help?


Update:

I tried the following and it worked beautifully:

echo "<html><body><table>\n\n";
$f = fopen("0001.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        foreach ($line as $cell) {
                echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";

Is it possible to skip the first two lines of the csv file, or better still, keep them separate from the table data which starts on line three?

like image 481
Seef Avatar asked Feb 25 '26 11:02

Seef


1 Answers

You need to read in the table so you can loop through it.

You will need to write some code to work out when the table starts. you might be able to loop through each line until you see "Pos" (as that is your table header).

In regards to the two lines of headers at the top of the file, you need to work out how you want to extract these and tokenise them. See the php manual for fgets() so you can read in each line. You can then explode() them as you please.

This is a way to do it...

<table>
<?php

// open the file
if (($handle = fopen("result - 0001.txt", "r")) !== false) {

    // TODO: use fgets() to find the row..


    // loop through each row
    while (($data = fgetcsv($handle, 0, "\t")) !== false) {

        echo "<tr>";

        for ($c = 0; $c < $num; $c++) 
        {
            echo "<td>" . $data[$c] . "</td>";
        }

        echo "</tr>";

    }

    // close file
    fclose($handle);
}
?>
</table>
like image 112
Michael Coxon Avatar answered Feb 28 '26 04:02

Michael Coxon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!