This time I will show you how to implement PHP data export, and what are the precautions for PHP data export implementation. The following is a practical case, let's take a look.
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. Then I found several solutions.Front-end solution
PHP cooperates with SheetJS/js-xlsx to export a large amount of Excel dataThe advantage of this solution is that it does not require additional interfaces, but it does Depends on front-end developers.Export to csv
This solution is faster and fully back-end implemented. The disadvantage is that the csv format has relatively high requirements on the export form. It requires pure data and cannot There are rich text forms such as images. The following mainly introduces how to export csvIntroduction to php official documentation<?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); ?>
Export complete example
<?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); ?>
Detailed explanation of the use of php namespace
thinkphp5 migrateDetailed explanation of database migration usage
The above is the detailed content of How to implement php data export. For more information, please follow other related articles on the PHP Chinese website!