Simple CSV to HTML Tables

free php tutorials, php classes, php utilities, free tools

In This Tutorial, We will learn how we can CSV into HTML Table format. for this purpose we use some functions

  • header function
  • fopen function that is used for open a file
  • eregi_replace function

Now we define a function viewlog()

function viewlog($filename) {
$fp = fopen($filename,"r");
$file = fread($fp,65535);
$replaced = eregi_replace(",", "<td>", $file);
$replaced2 = eregi_replace("\n", "<tr><td>", $replaced);
$replaced3 = eregi_replace("\r", "<tr><td>", $replaced2);
fclose($fp);

return $replaced3;
}

in this function, we opened a csv file, then we read all lines of this files and then we replaced \n \r , with tables tags, Now we call function at the end and and the top we will used header function, sample code is here

 

<?php $filename = ""; // File to open. quote out this variable if you are using a form to link to this script.

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// always modified
header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); // HTTP/1.0
/*
End of No cache
*/

function viewlog($filename) {
$fp = fopen($filename,"r");
$file = fread($fp,65535);
$replaced = eregi_replace(",", "<td>", $file);
$replaced2 = eregi_replace("\n", "<tr><td>", $replaced);
$replaced3 = eregi_replace("\r", "<tr><td>", $replaced2);
fclose($fp);

return $replaced3;
}
echo "<html><head><base href=\"./\"><title>CSV File Viewer</title></head><body bgcolor=silver>";
// Start the table definition of your choice
echo "<table border=0 bordercolor=black cellspacing=0 cellpadding=5 width=100% style='font-size:10pt'>";

echo viewlog($filename);
echo "</table></body></html>";
exit;
?>

Bookmark This Page