Search code examples
phphtmlhtml-table

Create HTML table from txt file


I have the following attempt at my function, but it's just printing out everything in the contacts.txt file on one line...

function contactsTable(){

  $file = fopen("contacts.txt", "r") or die("Unable to open file!");
  echo "<tr><th>";
  while (!feof($file)){
    echo "<tr><th>";
      $data = fgets($file); 
      echo "<tr><td>" . str_replace(',','</td><td>',$data) . '</td></tr>';
  }
  echo "<tr><th>";
  echo '</table>';
  fclose($file);
}

contacts.txt example like this;

Row 1 is headers --->  [value1, value2, value3, value4]
Row 2 is data --->     [value5, value6, value7, value8]

Is it possible to change my function so that Row 1 is using <th> tags so they are formatted as headers and the rest of the rows go into <td> tags for table data? I've tried to amend the logic but can't seem to get it.

TIA


Solution

  • Here is your contactsTable() function that prints the first contacts.txt line as table header and some basic HTML formatting for easy reading/debugging.

    function contactsTable() {
      $file = fopen('contacts.txt', 'r') or die('Unable to open file!');
      $row = 0;
    
      echo '<table>' . PHP_EOL;
    
      
      while (!feof($file)) {
        $row++;
        $data = fgets($file);
    
        if ($row === 1) {
          echo '<tr>' . PHP_EOL;
          echo '<th>' . str_replace(',', '</th><th>', $data) . '</th>' . PHP_EOL;
          echo '</tr>' . PHP_EOL;
        } else {
          echo '<tr>' . PHP_EOL;
          echo '<td>' . str_replace(',', '</td><td>', $data) . '</td>' . PHP_EOL;
          echo '</tr>' . PHP_EOL;
        }
      }
    
      echo '</table>' . PHP_EOL;
    
      fclose($file);
    }