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

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:
 
Name Age Sex
Cantor, Georg 163 M
Solutions in any language are welcome. asked Feb 6, 2009 at 1:44 26.8k 45 45 gold badges 155 155 silver badges 233 233 bronze badges

9 Answers 9

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

\n\n"; $f = fopen("so-csv.csv", "r"); while (($line = fgetcsv($f)) !== false) < echo ""; foreach ($line as $cell) < echo ""; > echo "\n"; > fclose($f); echo "\n
" . htmlspecialchars($cell) . "
";
answered Feb 6, 2009 at 2:56 286k 75 75 gold badges 466 466 silver badges 482 482 bronze badges Brilliant! Thank you so much. I think I'll go ahead and remove that link from the question then. Commented Feb 6, 2009 at 4:50 Just want to say, this is best code I've found so far - well done sir! Commented Dec 4, 2013 at 10:17 @phihag. Could you please provide an example to use your code? Thanks in advance Commented Mar 19, 2016 at 16:22 @ddpd You can create a new php file, insert this code, and run it. It's already an example ;) Commented Mar 20, 2016 at 14:53

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

function jj_readcsv($filename, $header=false) < $handle = fopen($filename, "r"); echo ''; //display header row if true if ($header) < $csvcontents = fgetcsv($handle); echo ''; foreach ($csvcontents as $headercolumn) < echo ""; > echo ''; > // displaying contents while ($csvcontents = fgetcsv($handle)) < echo ''; foreach ($csvcontents as $column) < echo ""; > echo ''; > echo '
$headercolumn
$column
'; 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.