Search code examples
phphtmlhtml-tableflat-file

Table in PHP with flatfile database


I'm trying to display the content of a text file in table format, with two columns and four rows:

Mateo;Pérez
Marcos;Martínez
Lucas;Télez
Juan;Pez

This is the PHP I'm using but the result is not the desired:

<?php

$course = file_get_contents("course.txt");
$line = explode("\n", $course);
for($i = 0; $i<count($line); $i++) {
    $item = explode(";", $line[$i]);
    {echo"

<table border='1' style='width:100%'>
  <tr>
    <td>".$item[0]."</td>
    <td>".$item[1]."</td>
  </tr>

</table>

";
    }
}
?>

This is what i get:

enter image description here


Solution

  • This might be what you want.

    <?php
    
    $course = file_get_contents("course.txt");
    $line = explode("\n", $course);
    
    echo "<table border='1' style='width:100%'>";
    
    for($i = 0; $i<count($line); $i++) 
    {
        $item = explode(";", $line[$i]);
        {
        echo "
        <tr>
            <td>".$item[0]."</td>
            <td>".$item[1]."</td>
        </tr>
        ";
        }
    }
    
    echo "</table>"
    
    ?>
    

    The problem you has is that you were looping the table as well as the TR and TD tags. So basically you had multiple tables, instead of one.