Convert a CSV-file to HTML table in PHP

You have a Comma Separated Value (CSV) file on the server and want to convert it to a HTML table. This example use the first row as a header. A simple way to ignore a header row is to let the counter ($row) start with a value greater than 1.

<?php

$row
= 1;
if ((
$handle = fopen("sites/default/files/Bok1.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++) {
           
//echo $data[$c] . "<br />\n";
           
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);
}
?>

The input of the following CSV...

aaaa;bbbb;cccc
1111;2222;3333
11;22;33

...becomes the following table:

<table border="1">
<thead>
  <tr><th>aaaa</th><th>bbbb</th><th>cccc</th></tr>
</thead>
<tbody>
  <tr><td>1111</td><td>2222</td><td>3333</td></tr>
  <tr><td>11</td><td>22</td><td>33</td></tr>
</tbody>
</table>

...and looks like this:

aaaa bbbb cccc
1111 2222 3333
11 22 33

 

Knowledge keywords: