Latest Post

Error: No input file specified.

While trying to run a codeigniter app the other day I came across this error just after I had finished uploading the files and making the ne...

Tuesday, August 3, 2010

PHP: Exporting a mySQL table to CSV

$rsSearchResults = mysql_query($sql, $connDb) or die(mysql_error());

$out = '';
$fields = mysql_list_fields('dbname','tablename',$connDb);
$columns = mysql_num_fields($fields);

// Put the name of all fields
for ($i = 0; $i < $columns; $i++) {
$l=mysql_field_name($fields, $i);
$out .= '"'.$l.'",';
$out .="\n";

// Add all values in the table
while ($l = mysql_fetch_array($rsSearchResults)) {
for ($i = 0; $i < $columns; $i++) {
$out .='"'.$l["$i"].'",';
$out .="\n";
// Output to browser with appropriate mime type, you choose ;)
$filedate = date('d-m-Y');
header("Content-type: text/x-csv");
//header("Content-type: text/csv");
//header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=filename-$filedate.csv");
echo $out;

If you wish to write the output to a file on the server instead then use file manipulation functions fopen() and fwrite()

No comments:

Post a Comment

Chitika Ads