Home > Backend Development > PHP Tutorial > excel2010 official download free full version PHP export MySQL data to Excel file fputcsv

excel2010 official download free full version PHP export MySQL data to Excel file fputcsv

WBOY
Release: 2016-07-29 08:45:54
Original
1430 people have browsed it

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);
}


Advantages: Simple and easy to use, very memory-saving, and does not rely on third-party libraries.

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.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template