Convert an HTML table to CSV using PHP

Here is a tutorial to convert a HTML table to CSV using php. To do this, we will need two php files:

1. table.php (where you create your table)
2. export.php (which converts your table to csv and let it download)

Let’s say that you have two column table that you make via MySql table:

$output .= "<table>";

	$output .= "<th>Year</th>";
        $output .= "<th>Date</th>";

	while($result_array=mysql_fetch_array($query)) {
		$output .= "<tr>";
		        $output .= "<td>$result_array[0]</td>";
		        $csv_output .= $result_array[0] . ", ";

		        $output .= "<td>$result_array[1]</td>";
		        $csv_output .= $result_array[1] . "\n";
		$output .= "</tr>";
	}
$output .= "</table>";

$csv_hdr = "Year, Date";

Now we need to pass $csv_hdr and $csv_output to export.php via table.php:

<form name="export" action="export.php" method="post">
	<input type="submit" value="Export table to CSV">
	<input type="hidden" value="<? echo $csv_hdr; ?>" name="csv_hdr">
	<input type="hidden" value="<? echo $csv_output; ?>" name="csv_output">
</form>

In export.php do:

<?php

//First we'll generate an output variable called out. It'll have all of our text for the CSV file.

$out = '';

//Next we'll check to see if our variables posted and if they did we'll simply append them to out.

if (isset($_POST['csv_hdr'])) {

$out .= $_POST['csv_hdr'];

$out .= "\n";

}

if (isset($_POST['csv_output'])) {

$out .= $_POST['csv_output'];

}

//Now we're ready to create a file. This method generates a filename based on the current date & time.

$filename = $file."_".date("Y-m-d_H-i",time());

//Generate the CSV file header

header("Content-type: application/vnd.ms-excel");

header("Content-disposition: csv" . date("Y-m-d") . ".csv");

header("Content-disposition: filename=".$filename.".csv");

//Print the contents of out to the generated file.

print $out;

//Exit the script

exit;

?>
Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*