ZimplicIT

Convert a CSV-file to HTML table in PHP

You have a Comma Separated Value file on 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:

aaaabbbbcccc
111122223333
112233

Comments

I have added an IF

Hi I have added an IF statement that adds a non braking space if the value is empty. Regarding add and edit data to a table after it has been rendered is possible with jQueary, I guess a search on Google will give you a good example or plugin to use. http://stackoverflow.com has some good answers

empty cell and use non-breaking spaces

hi, thank you for your script. i am new to php and i am actually converting my csv file into html table but i found that there are an empty space and i did like to make it as non breaking spaces but i don't know where to add the code. i am using your program to convert my csv file to html table. another question, is it possible to add row and edit data after converting to html table??i read it somewhere we can but eemmm i just can't figure it out(been struggling with this for a week now:( ).thanks a million for your help and the coding... have a nice day...

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.