高效率的php 导出 xls,csv 的方法
高效的php 导出 xls,csv 的方法
经常会碰到需要从数据库中导出数据到Excel文件,用一些开源的类库,比如PHPExcel,确实比较容易实现,但对大量数据的支持很不好,很容易到达PHP内存使用上限。这里的方法是利用fputcsv写CSV文件的方法,直接向浏览器输出Excel文件。
<?php // 输出Excel文件头,可把user.csv换成你要的文件名header('Content-Type: application/vnd.ms-excel');header('Content-Disposition: attachment;filename="user.csv"');header('Cache-Control: max-age=0');include './Mysql.class.php';//mysql 用你自己的操作类就可以$db = new mysql();// 从数据库中获取数据,为了节省内存,不要把数据一次性读到内存,从句柄中一行一行读即可$sql = 'select id,user_login from wp_users';$stmt = $db->getAll($sql); // 打开PHP文件句柄,php://output 表示直接输出到浏览器$fp = fopen('php://output', 'a'); // 输出Excel列名信息$head = array("id", "姓名");foreach ($head as $i => $v) { // CSV的Excel支持GBK编码,一定要转换,否则乱码 $head[$i] = iconv('utf-8', 'gbk', $v);} // 将数据通过fputcsv写到文件句柄fputcsv($fp, $head); // 计数器$cnt = 0;// 每隔$limit行,刷新一下输出buffer,不要太大,也不要太小$limit = 100000; // 逐行取出数据,不浪费内存$count = count($stmt);for($t=0;$t $v) { $row[$i] = iconv('utf-8', 'gbk', $v); } fputcsv($fp, $row);}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

To work on file upload we are going to use the form helper. Here, is an example for file upload.

In this chapter, we are going to learn the following topics related to routing ?

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

Validator can be created by adding the following two lines in the controller.

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide
