Recently I am working on a backend management project, and there is usually a need to export data to excel in the backend. After previous searches, it is usually recommended to use php excel. I often use laravel, and there is also a very useful corresponding package for php excel.
It is very easy to use at first, but when the data that needs to be exported reaches tens of thousands, it will directly cause the problem of insufficient memory.
The advantage of this solution is that it does not require additional interfaces, but it depends on the front-end developer.
Export to csv
This solution is faster and fully back-end implemented. The disadvantage is that the csv format has relatively high requirements for the export form. The requirement is pure data, and there cannot be rich text forms such as pictures.
The following mainly introduces how to export csv
<?php $list = array ( array('aaa', 'bbb', 'ccc', 'dddd'), array('123', '456', '789'), array('"aaa"', '"bbb"') ); $fp = fopen('file.csv', 'w'); foreach ($list as $fields) { fputcsv($fp, $fields); } fclose($fp); ?>
<?php $name = 'test'; header ( "Content-type:application/vnd.ms-excel" ); header ( "Content-Disposition:filename=".$name.".csv" ); header ('Cache-Control: max-age=0'); //打开PHP文件句柄,php://output 表示直接输出到浏览器 $fp = fopen('php://output', 'a'); // 写入BOM头,防止乱码 fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF)); // 生成的测试数据 function test() { for ($i=0; $i < 150000; $i++) { yield ['name', $i, '男']; } } // 表头 $headers = ['名字', '年龄', '性别']; fputcsv($fp, $headers); foreach (test() as $value) { fputcsv($fp, $value); } fclose($fp); ?>
It is convenient to use with chunk in laravel Quickly export all data.
Related recommendations:
Detailed explanation of PHP data export knowledge points
Problems with PHP data export and WEB service
Problems related to PHP data export and WEB service
The above is the detailed content of Detailed explanation of php data export. For more information, please follow other related articles on the PHP Chinese website!