Home > Software engineering >  Display a CSV file as an HTML table with header on the left
Display a CSV file as an HTML table with header on the left

Time:07-19

This is the output of my current code: enter image description here

I was wondering if its possible to have the header on the left and the data from a csv file to be on the right? This is the best example I can find on how I would like the table to be.

enter image description here

For reference, here is my code:

<?php

$row = 1;
if (($handle = fopen("Book1.csv", "r")) !== FALSE) {
   
    echo '<table border="1">';
   
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        if ($row == 1) {
            echo '<thead><tr>';
        }else{
            echo '<tr>';
        }
       
        for ($c=0; $c < $num; $c  ) {
            if(empty($data[$c])) {
               $value = "&nbsp;";
            }else{
               $value = $data[$c];
            }
            if ($row == 1) {
                echo '<th>'.$value.'</th>';
            }else{
                echo '<td>'.$value.'</td>';
            }
        }
       
        if ($row == 1) {
            echo '</tr></thead><tbody>';
        }else{
            echo '</tr>';
        }
        $row  ;
    }
   
    echo '</tbody></table>';
    fclose($handle);
}
?>

This is how my csv file looks like:

enter image description here

CodePudding user response:

This can be done with a table with vertical headings, here is a basic example:

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
th, td {
  padding: 5px;
  text-align: left;
}
</style>
</head>
<body>

<h2>Vertical Headings:</h2>

<table style="width:100%">
  <tr>
    <th>Name:</th>
    <td>Bill Gates</td>
    <td>Steve Jobs</td>
  </tr>
  <tr>
    <th>Telephone:</th>
    <td>555 77 854</td>
    <td>123 77 854</td>
  </tr>
  <tr>
    <th>Telephone:</th>
    <td>555 77 855</td>
    <td>543 77 855</td>
  </tr>
</table>

</body>
</html>

To populate the table with php you can do it like this:

$file = fopen("Book1.csv","r");
$data = array();
while($row = fgetcsv($file)) {
   $data[] = $row; //Get all the data
}
if($data){
    $n_columns = count($data[0]); //Get number of columns
}
echo '<table border="1">';
for ($col = 0; $col < $n_columns; $col  ) {
    echo '<tr>';
    foreach ($data as $row_k => $row) {
        if ($row_k == 0) {
            echo '<th>';
        } else {
            echo '<td>';
        }

        echo $row[$col] ?? '';
        if ($row_k == 0) {
            echo '</th>';
        } else {
            echo '</td>';
        }
    }
    echo '</tr>';
}
echo '</table>';

fclose($file);

Result:

enter image description here

  • Related