Export MySQL data to Excel in PHP

[expired user #11803]'s profile image [expired user #11803] posted 5 years ago in General Permalink

I'm trying to get my MySQL data to Excel file, but I'm having problems with Excel cells. All my text goes to one cell, I would like to have each row value in separate Excel cell. Here is my code:

1 attachment(s):
  • 5
[expired user #1502]'s profile image [expired user #1502] posted 5 years ago Permalink

I do not really know how it is related to Heidi, but... You can try to do something like this:

$f = fopen('php://temp/maxmemory:' . (5*1024*1024), 'w');
while($row = mysql_fetch_row($result)) fputcsv($f, $row, ',', '"');
fseek($f, 0);

// todo@ no data

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment, filename=export.csv' . $s);
// todo@ set headers to prevent caching
fpassthru($f);
[expired user #1502]'s profile image [expired user #1502] posted 5 years ago Permalink

Some fixes (I have not checked the code so feel free to fix errors if any)

$f = fopen('php://temp/maxmemory:' . (5*1024*1024), 'w'); // creating in-memory resource
// todo@ add headers to $f, you may also use fputcsv (see below)
while($row = mysql_fetch_row($result)) fputcsv($f, $row, ',', '"'); // this will escape your values
fseek($f, 0);
// todo@ message if no data
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=export.csv');
// todo@ set additional headers to prevent caching
fpassthru($f); // return data, you do not need to build content manually

Please login to leave a reply, or register at first.