Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically display a CSV file as an HTML table on a web page

Tags:

html

php

csv

I'd like to take a CSV file living server-side and display it dynamically as an html table. E.g., this:

Name, Age, Sex "Cantor, Georg", 163, M 

should become this:

<html><body><table> <tr> <td>Name</td> <td>Age</td> <td>Sex</td> </tr> <tr> <td>Cantor, Georg</td> <td>163</td> <td>M</td> </td> </table></body></html> 

Solutions in any language are welcome.

like image 281
dreeves Avatar asked Feb 06 '09 01:02

dreeves


People also ask

How do I convert CSV data to HTML?

First the CSV File i.e. Comma separated Text file, will be read using HTML5 FileReader API as String. Then the String will be parsed into Rows and Columns and will be displayed in HTML Table. The HTML Markup consists of a FileUpload control (HTML File Input) and a HTML Button i.e. Upload.

How do I download a table from CSV to my website?

Right click on the table, then select 'Download table as CSV' from the context menu. The extension downloads the HTML tables in MS Excel style CSV format. Images will be show in the CSV file as the source URL.


2 Answers

The previously linked solution is a horrible piece of code; nearly every line contains a bug. Use fgetcsv instead:

<?php echo "<html><body><table>\n\n"; $f = fopen("so-csv.csv", "r"); while (($line = fgetcsv($f)) !== false) {         echo "<tr>";         foreach ($line as $cell) {                 echo "<td>" . htmlspecialchars($cell) . "</td>";         }         echo "</tr>\n"; } fclose($f); echo "\n</table></body></html>"; 
like image 156
phihag Avatar answered Sep 18 '22 18:09

phihag


Here is a simple function to convert csv to html table using php:

function jj_readcsv($filename, $header=false) { $handle = fopen($filename, "r"); echo '<table>'; //display header row if true if ($header) {     $csvcontents = fgetcsv($handle);     echo '<tr>';     foreach ($csvcontents as $headercolumn) {         echo "<th>$headercolumn</th>";     }     echo '</tr>'; } // displaying contents while ($csvcontents = fgetcsv($handle)) {     echo '<tr>';     foreach ($csvcontents as $column) {         echo "<td>$column</td>";     }     echo '</tr>'; } echo '</table>'; fclose($handle); } 

One can call this function like jj_readcsv('image_links.csv',true);

if second parameter is true then the first row of csv will be taken as header/title.

Hope this helps somebody. Please comment for any flaws in this code.

like image 30
Joby Joseph Avatar answered Sep 20 '22 18:09

Joby Joseph