PHP does not use the Open source class library to export MySQL data to an Excel file

Source: Internet
Author: User
Tags stmt
  1. Output 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 the data from the database, in order to save memory, do not read the data once to the memory, the subordinate handle in a row to read
  6. $sql = ' SELECT * from tbl where ... ';
  7. $stmt = $db->query ($sql);
  8. Open PHP file handle, php://output direct output to browser
  9. $fp = fopen (' php://output ', ' a ');
  10. Output Excel Column name information
  11. $head = Array (' name ', ' gender ', ' age ', ' Email ', ' phone ', ' ... ');
  12. foreach ($head as $i = = $v) {
  13. CSV Excel support GBK encoding, be sure to convert otherwise garbled
  14. $head [$i] = iconv (' utf-8 ', ' GBK ', $v);
  15. }
  16. Writes data to a file handle via 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. Row-by-line data extraction without wasting memory
  23. while ($row = $stmt->fetch (zend_db::fetch_num)) {
  24. $cnt + +;
  25. if ($limit = = $cnt) {//Refresh output buffer to prevent problems caused by excessive data
  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, but also save memory, and do not rely on the third-party class library, the need for friends to try it out on their own.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.