zoukankan      html  css  js  c++  java
  • php导出数据为CSV文件DEMO

    代码示例:

        private function _download_send_headers($filename) {
            // disable caching
            $now = gmdate("D, d M Y H:i:s");
            header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
            header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
            header("Last-Modified: {$now} GMT");
    
            // force download
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");
    
            // disposition / encoding on response body
            header("Content-Disposition: attachment;filename={$filename}");
            header("Content-Transfer-Encoding: binary");
        }
    
        private function _array2csv($array) {
            if (count($array) == 0) {
                return null;
            }
            $keys = array_keys(reset($array));
            echo implode(',', $keys) . PHP_EOL;
            for ($i = 0, $j = count($array); $i < $j; $i++) {
                echo implode(',', $array[$i]) . PHP_EOL;
            }
        }
    
        public function saveAsCsv() {
                $this -> _download_send_headers("data_export_" . date("Y-m-d") . ".csv");
                $ret = array(
                    array(
                        'id' => 1,
                        'name' => 'hello'
                    ),
                    array(
                        'id' => 2,
                        'name' => 'world'
                    ),
                    array(
                        'id' => 3,
                        'name' => 'good'
                    ),
                );
                $this -> _array2csv($ret);
                die();
        }

    当然还有用fputcsv的,但我试了一下效果不太好。

  • 相关阅读:
    格子刷油漆【动态规划问题】—NYOJ 980
    Throughput Controller
    CSV Data Set Config 详细使用说明
    nmap使用笔记
    记三个有趣的漏洞
    Windows添加右键新增.md文件
    文件上传绕过WAF
    bypass_safedog
    漏洞挖掘之爆破的艺术
    特殊后缀上传(为什么用白名单不用黑名单)
  • 原文地址:https://www.cnblogs.com/lurenjiashuo/p/php-export-to-csv.html
Copyright © 2011-2022 走看看