Home > Backend Development > PHP Tutorial > PHP does not use open source libraries to export mysql data to Excel files

PHP does not use open source libraries to export mysql data to Excel files

WBOY
Release: 2016-07-25 09:07:11
Original
1183 people have browsed it
  1. // Output the Excel file header, you can replace user.csv with the file name you want
  2. header('Content-Type: application/vnd.ms-excel');
  3. header( 'Content-Disposition: attachment;filename="user.csv"');
  4. header('Cache-Control: max-age=0');
  5. // Get data from the database. In order to save memory, do not put the data Read the memory at one time and read it line by line from the handle
  6. $sql = 'select * from tbl where ...';
  7. $stmt = $db->query($sql);
  8. // Open the PHP file Handle, php://output means output directly to the browser
  9. $fp = fopen('php://output', 'a');
  10. // Output Excel column name information
  11. $head = array('name' , 'Gender', 'Age', 'Email', 'Telephone', '...');
  12. foreach ($head as $i => $v) {
  13. // Excel for CSV supports GBK encoding, must be Convert, otherwise garbled characters
  14. $head[$i] = iconv('utf-8', 'gbk', $v);
  15. }
  16. // Write the data to the file handle through fputcsv
  17. fputcsv($fp, $head );
  18. //Counter
  19. $cnt = 0;
  20. // Every $limit line, refresh the output buffer, not too big, not too small
  21. $limit = 100000;
  22. // Take out the data line by line, Don’t waste memory
  23. while ($row = $stmt->fetch(Zend_Db::FETCH_NUM)) {
  24. $cnt ++;
  25. if ($limit == $cnt) { //Refresh the output buffer to prevent Too much data causes problems
  26. ob_flush();
  27. flush();
  28. $cnt = 0;
  29. }
  30. foreach ($row as $i => $v) {
  31. $row[$i] = iconv(' utf-8', 'gbk', $v);
  32. }
  33. fputcsv($fp, $row);
  34. }
Copy code

Easy to use, saves memory, and does not rely on third-party libraries , friends in need, please try it yourself.



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