I need to export the results of a MySQL query to an Excel file. I picked up some code to achieve this, but there is one issue. The code sends the header information to the browser with the .xls content type and the query results following the headers. The code for the called page is as follows:
<?php
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/?
/", "\
", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "customer_inventory_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
$query = "SELECT customer_id,sku,qtyoh,date FROM sims_customer_inventory WHERE customer_id=$customer_id and date=(select max(date) from sims_customer_inventory)";
$result = mysql_query($query, $conn) or die(mysql_error());
while(false !== ($row = mysql_fetch_assoc($result))) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "
";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "
";
?>
The problem is that when the page is called in this form:
<form action="inventory_download.php" method="get" onsubmit="return validateInventoryform();">
The file does not automatically download. However, when I refresh the page the file downloads. My problem is that when the page is called this should automatically execute the code to download the file. It does not do that. I have looked all over the internet to solve the problem, but I can't find out why it does not work.