Export html table as csv

PHP One response so far

A comma-separated values (CSV) file is a simple file format that is widely supported, so it is often used to move tabular data between different computer programs that support the format. CSV file is a text format for a database table. Each record in the table is one line of the text file. Each field value of a record is separated from the next with a comma. For example, a CSV file might be used to transfer information from a database to a spreadsheet or another database.

In the following script, html data (populated by database query) is getting exported in a csv file format.

<?
$str='select name,email,date from table';
$arr=array('Name','Email','Date');
?>

<form action="export.php" method="post">
<input type="hidden" name="csv" value="yes" />
<input type="hidden" name="query" value="<? echo($str) ?>" />
<?
foreach ($arr as $key => $value)
{
echo "<input type="hidden" name="arr[$key]" value="$value">n";
}
?>
<input type="image" src="csv.jpg" width="35" height="35" />
</form>

Here $str is the database query which is executed in export.php page and $arr holds the column titles of the csv file.These data are stored in hidden fields to  “post” to export.php.

Below is the export.php file code:

<?
include("config.php"); // database connectivity code
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$fp = fopen('php://output', 'w');
fputcsv($fp, $_POST['arr']);
$query=stripslashes($_POST['query']);
$q1=mysql_query($query)or die(mysql_error());
while ($row1 = mysql_fetch_assoc($q1)) fputcsv($fp, $row1);
?>
The following two tabs change content below.
I am a core php developer and web designer working as a freelancer in elance,odesk etc.

Latest posts by Mudit (see all)

  • Dan Grabowski

    What is included in the config.php file? I tried replacing it with server connection info, but it only returned  in cell A1

x
Loading...