The method here is to use fputcsv to write CSV files and directly output Excel files to the browser.
Copy the code The code is as follows:
// Output the Excel file header, you can replace user.csv with the file name you want
header('Content-Type: application/vnd.ms-excel') ;
header('Content-Disposition: attachment;filename="user.csv"');
header('Cache-Control: max-age=0');
// Get data from the database, in order to save memory, Don't read the data into the memory at once, just read it line by line from the handle
$sql = 'select * from tbl where ...';
$stmt = $db->query($sql);
// Open PHP file handle, php://output means output directly to the browser
$fp = fopen('php://output', 'a');
// Output Excel column name information
$head = array('Name ', 'Gender', 'Age', 'Email', 'Telephone', '...');
foreach ($head as $i => $v) {
// CSV Excel supports GBK encoding, must Convert, otherwise garbled characters
$head[$i] = iconv('utf-8', 'gbk', $v);
}
// Write the data to the file handle through fputcsv
fputcsv($fp, $head );
// Counter
$cnt = 0;
// Every $limit line, refresh the output buffer, not too big, not too small
$limit = 100000;
// Take out data line by line, no waste Memory
while ($row = $stmt->fetch(Zend_Db::FETCH_NUM)) {
$cnt ++;
if ($limit == $cnt) { //Refresh the output buffer to prevent excessive data Causing problems
ob_flush();
flush();
$cnt = 0;
}
foreach ($row as $i => $v) {
$row[$i] = iconv('utf-8' , 'gbk', $v);
}
fputcsv($fp, $row);
}
The above introduces how to export MySQL data to Excel file fputcsv with PHP, which is the official download of excel2010. The free full version includes the content of the official download of excel2010, free full version. I hope it will be helpful to friends who are interested in PHP tutorials.