Home > Backend Development > PHP Tutorial > Detailed explanation of how to efficiently export Excel (CSV) with PHP

Detailed explanation of how to efficiently export Excel (CSV) with PHP

藏色散人
Release: 2023-04-09 22:56:01
forward
8403 people have browsed it

This article will introduce how to efficiently export Excel (CSV) with PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

CSV, which is Comma Separated Value (Comma separated value ), usually plain text files.

If you export Excel without any advanced usage, just export data, then it is recommended to use this method, which is better than PHPexcel Much more efficient.

It takes about 2 to 3 seconds to export 200,000 data.

 /**
 * 导出excel(csv)
 * @data 导出数据
 * @headlist 第一行,列名
 * @fileName 输出Excel文件名
 */
function csv_export($data = array(), $headlist = array(), $fileName) {
  
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="'.$fileName.'.csv"');
    header('Cache-Control: max-age=0');
  
    //打开PHP文件句柄,php://output 表示直接输出到浏览器
    $fp = fopen('php://output', 'a');
    
    //输出Excel列名信息
    foreach ($headlist as $key => $value) {
        //CSV的Excel支持GBK编码,一定要转换,否则乱码
        $headlist[$key] = iconv('utf-8', 'gbk', $value);
    }
  
    //将数据通过fputcsv写到文件句柄
    fputcsv($fp, $headlist);
    
    //计数器
    $num = 0;
    
    //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
    $limit = 100000;
    
    //逐行取出数据,不浪费内存
    $count = count($data);
    for ($i = 0; $i < $count; $i++) {
    
        $num++;
        
        //刷新一下输出buffer,防止由于数据过多造成问题
        if ($limit == $num) { 
            ob_flush();
            flush();
            $num = 0;
        }
        
        $row = $data[$i];
        foreach ($row as $key => $value) {
            $row[$key] = iconv('utf-8', 'gbk', $value);
        }

        fputcsv($fp, $row);
    }
  }
Copy after login
recommends: "PHP Video Tutorial"

The above is the detailed content of Detailed explanation of how to efficiently export Excel (CSV) with PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
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