I have a list of names (first and last) along with their emails saved onto a .txt. file. I am trying to output the data and format it within a table, but it doesn't seem to come out correctly.

Text file:
John Doe
jdoe@email.com
Jane Smith
jsmith@email.com

PHP/HTML:

<table>
    <tr>
        <td>Name:</td>
        <td>Email:</td>
    </tr>
<?php
    $contents = file("File.txt");
    $lines = count($contents);

while($lines != 0) {
    echo "<tr>";
    foreach($contents as $field) {
        echo "<td>" . $field . "</td>";
    }
    echo "<tr>";
    $lines--;
}
?>
</table>

Ouput:
Name: Email:
John Doe
jdoe@email.com
Jane Smith
jsmith@email.com

No matter what I do, everything is entered in a new row. Any suggestions? Thanks in advance.

    The problem is that there is nothing in your loops to say how many items should go on one row (two? three? one? fifty?).

    $contents = file('file.txt');
    $contents = array_chunk($contents, 2);
    foreach($contents as $row)
    {
        echo '<tr>';
        foreach($row as $field)
        {
            echo '<td>', $field, '</td>';
        }
        echo '</tr>';
    }

      Just in case, you might want to ignore any empty lines in the input file:

      $contents = file('file.txt', FILE_SKIP_EMPTY_LINES);
      
        Write a Reply...