PHP export to Excel file gives me source code in columns
I feel like I'm making a simple mistake but I can't seem to figure out what.
I have some code for exporting a mySQL table to an Excel file.
However, when I do the export, the entire HTML source code gets exported along with my data. I open the file in Excel and my table data in there but it's also got all the HTML inside.
What could be causing all the source code to be exported along with the data?
I should mention that I'm using this code as part of a Wordpress plugin I'm writing. When I test the export outside wordpress, it works fine. But 开发者_如何学Gowhen I try to export from a Wordpress admin page, I get all the extra HTML source code.
Try this code.
$host = 'localhost';
$user = 'mysqlUser';
$pass = 'myUserPass';
$db = 'myDatabase';
$table = 'products_info';
$file = 'export';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$res = mysql_query("SELECT * FROM $table");
// fetch a row and write the column names out to the file
$row = mysql_fetch_assoc($res);
$line = "";
$comma = "";
foreach($row as $name => $value) {
$line .= $comma . '"' . str_replace('"', '""', $name) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
// remove the result pointer back to the start
mysql_data_seek($res, 0);
// and loop through the actual data
while($row = mysql_fetch_assoc($res)) {
$line = "";
$comma = "";
foreach($row as $value) {
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
}
fclose($fp);
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="export.csv"');
readfile('export.csv');
Thanks,
Kanji
精彩评论