Вам понадобятся соответствующие заголовки (приведенные ниже взяты из примера в документации по PHP)
$export = "my_name.xls";
header('Pragma: public');
/////////////////////////////////////////////////////////////
// prevent caching....
/////////////////////////////////////////////////////////////
// Date in the past sets the value to already have been expired.
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate'); // HTTP/1.1
header('Cache-Control: pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
header ("Pragma: no-cache");
header("Expires: 0");
/////////////////////////////////////////////////////////////
// end of prevent caching....
/////////////////////////////////////////////////////////////
header('Content-Transfer-Encoding: none');
// This should work for IE & Opera
header('Content-Type: application/vnd.ms-excel;');
// This should work for the rest
header("Content-type: application/x-msexcel");
header('Content-Disposition: attachment; filename="'.basename($export).'"');
После этого ваш код должен работать с парой модификаций.(Excel может читать структуры HTML):
error_reporting (E_ALL ^ E_NOTICE); // you shouldn't have that in the loop.
// you actually should put this first
echo "<table >"
// the rest of your table opening code.
$alt_color = 0;
while($row = mysql_fetch_array($result))
{
echo "<tr>";
// the rest of your columns.
echo "</tr>";
}
echo "</table>";
Если по какой-то причине это не сработает, вы можете создать CSV, но вам нужно беспокоиться о том, чтобы его избежать:
// add all of the headers.
echo '"ComputerName","SerialNumber","SystemModel",'; //etc for all columns.
// row makes sure that there is only one set of values.
$row = mysql_fetch_row($result);
if( !$row ) die(); // no value found. exit.
echo getCSVRow( $row );
do // do...while lets us handle the \n more gracefully.
{
echo "\n". getCSVRow( $row );
} while ($row = mysql_fetch_row($result));
function getCSVRow( array $row )
{
$ret = "";
foreach( $row as $val )
$ret .= '"' . escapeCSV( $val ) . '",';
return sustr( $ret, 0, strlen( $ret ) ); // clear the tailing comma
}
function escapeCSV( $str )
{
return str_replace( '"', '\"', $str );
}