Export MySQL data to Excel in PHP

tutu10 posted 2 months ago in General

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
Misha v.3 posted 2 months ago

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);
Misha v.3 posted 2 months ago

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.