Welp, I guess since everyone is posting code.... this is a bit of code from a project I did. It emits a csv file, which isn't real excel, but excel will open it automatically:
if ($mode=='csv')
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="file.csv"');
echo csv($tab);
exit;
}
/**
* Emit a csv version of the tab.
*/
function csv($tab)
{
global $tabpath;
$dq = '"';
$file = file_get_contents( "$tabpath/$tab" );
$file = normalize( $file );
list( $totalHours, $rate, $total, $litFile, $error ) = calculate( $file );
$lines = preg_split( '/\n/s', $file );
foreach( $lines as $line )
{
$parts = preg_split('/ - /', $line);
$o .= $dq.$parts[0].$dq.',';
$o .= $dq.$parts[1].$dq.',';
$o .= $dq.$parts[2].$dq.',';
$o .= $dq.csvquote($parts[3]).$dq.',';
$o .= $dq.preg_replace('/ minutes/','',$parts[4]).$dq.',';
$o .= "\r\n";
}
return $o;
}
function csvquote( $s )
{
$s = preg_replace('/"/','""', $s);
return $s;
}
I would modify the csv function like this. It takes a mysql result as an argument:
/**
* Emit a csv version of the result.
*/
function csv($result)
{
$dq = '"';
while( $row = mysql_fetch_row($result) )
{
while( list($key,$value) = each($row) )
{
$o .= $dq.csvquote($value).$dq;
}
$o .= "\r\n";
}
return $o;
}