Link to home
Start Free TrialLog in
Avatar of nisupport
nisupport

asked on

Export mysql query results to excel from a php page

I am trying to export mysql results from a php page to excel. I have been trying different code I have found online, but a consistent error I get is: Warning: Cannot modify header information - headers already sent by (output started at D:\Inetpub\wwwroot\dealernet\admin\download.php:1) in D:\Inetpub\wwwroot\dealernet\admin\download.php on line 18

Warning: Cannot modify header information - headers already sent by (output started at D:\Inetpub\wwwroot\dealernet\admin\download.php:1) in D:\Inetpub\wwwroot\dealernet\admin\download.php on line 19

Here is the coded page: (admin_eyedoo.php contains the connection string)
 <?
include ("admin_eyedoo.php");
$queryexport = "SELECT * FROM p_eventlog WHERE event = '$eventid'"; //second for list
                                    $export = mysql_query($queryexport) or die ("Error in query: $queryexport. " . mysql_error());
                                    
$tsv  = array();
$html = array();
while($row = mysql_fetch_array($export, MYSQL_NUM))
{
   $tsv[]  = implode("\t", $row);
   $html[] = "<tr><td>" .implode("</td><td>", $row) .              "</td></tr>";
}

$tsv = implode("\r\n", $tsv);
$html = "<table>" . implode("\r\n", $html) . "</table>";

$fileName = 'mysql-to-excel.xls';
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$fileName");

echo $tsv;
//echo $html;

mysql_close($connection);
                                ?>
ASKER CERTIFIED SOLUTION
Avatar of Aamir Saeed
Aamir Saeed
Flag of Pakistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi nisupport,
As I know, the error you get is cause by before you write these two line:
    header("Content-type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=$fileName");
the header information already been set. Make sure only set the header information for once, then no such error message will be prompt out.

Regards,
eechincs