Home > Backend Development > PHP Tutorial > PHP export CSV file

PHP export CSV file

WBOY
Release: 2016-08-08 09:26:41
Original
1136 people have browsed it

Reprint: http://blog.csdn.net/huyanping/article/details/7068356

We often encounter the need to export data from a database to an Excel file. Using some open source libraries, such as PHPExcel, is indeed easier to implement, but the support for large amounts of data is very poor, and it is easy to reach the upper limit of PHP memory usage. The method here is to use fputcsv to write CSV files and directly output Excel files to the browser.
 
  // 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, do not read the data into the memory at once, from the handle Just read it line by line
  $sql = 'select * from tbl where...';
  $stmt = $db->query($sql);
   // Open the PHP file handle, php://output means direct output Go 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, be sure to convert, otherwise garbled characters
  $head[$i] = iconv('utf-8', 'gbk', $v);
 }
  // Write data to the file handle through fputcsv
  fputcsv($fp, $head);
  // Counter
  $cnt = 0;
  // Refresh the output buffer every $limit line, not too big or too small
  $limit = 100000;
  // Take out the data line by line without wasting memory
 while ($row = $stmt-> fetch(Zend_Db::FETCH_NUM)) {
 $cnt ++;
 if ($limit == $cnt) { //Refresh the output buffer to prevent problems caused by too much data
 ob_flush();
 flush();
  $cnt = 0;
  }
 foreach ($row as $i => $v) {
  $row[$i] = iconv('utf-8', 'gbk', $v);
  }
fputcsv($fp, $row);
 }

The above introduces the export of CSV files with PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
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