PHP數據導出CSV格式文件

前言:

       之前在做數據導出功能時一直使用PHPexcel進行處理的,這個的功能還是比較強大的,但是比較沉重,在數據量比較打時,還是比較吃內存的。經常會遇到超時或者內存不足。解決方式都是網上的幾種,百度google一大推,供參考。github傳送地址 https://github.com/PHPOffice/PHPExcel

       由於就是數據導出,所以後面使用了導出csv格式數據,摒棄了PHPExcel。導出大量數據時可以將數據進行分批量的導出,防止數組內容過大佔內存而導致的報錯。

        $headArr = ['用戶ID', '姓名', '手機號', '手機歸屬地', '定位城市', '選定車位', '價格(元)', '關注車位', '參與時間'];

        set_time_limit(0);
        //文件名
        $filename = $activity_info['name'] . "用戶名單.csv";
        //直接輸出到瀏覽器
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename);
        header('Cache-Control: max-age=0');
        $fp = fopen('php://output', 'a');
        //寫入頭部標題
        $csv_header = [];
        for ($i = 0; $i < count($headArr); $i++) {
            array_push($csv_header, mb_convert_encoding($headArr[$i], 'gb2312', 'utf-8'));//注意編碼問題,若使用icovn部分轉碼失敗直接返回空
        }
        fputcsv($fp, $csv_header);

        //進行分頁獲取,每頁獲取
        $limit = 1000;
        for ($page = 1; $page < 40; $page++) {
            $list = $signupModel->getParkingUserList($condition, $page, $limit);
            if (empty($list['data'])) {
                break;
            }
            foreach ($list['data'] as $key => $val) {
                $tmp = [];
                $tmp['signup_id'] = $val['signup_id'];//用戶ID
                $tmp['username'] = $val['username'] ? str_replace("null", "", $val['username']) : '-';//選定用戶
                $tmp['username'] = mb_convert_encoding($tmp['username'], 'gb2312', 'utf-8');//用戶名稱
                $tmp['mobile'] = $val['mobile'] ? $val['mobile'] : '-';
                $tmp['mobile_city'] = $val['mobile_city'] ? $val['mobile_city'] : '-';//手機歸屬地
                $tmp['mobile_city'] = mb_convert_encoding($tmp['mobile_city'], 'gb2312', 'utf-8');
                $tmp['ip_city'] = $val['ip_city'] ? $val['ip_city'] : '-';//定位城市
                $tmp['ip_city'] = mb_convert_encoding($tmp['ip_city'], 'gb2312', 'utf-8');
                $tmp['parking_id'] = $val['parking_id']?$val['parking_id'].'('.$val['car_no'].')':'';//選定車號
                $tmp['parking_id'] = mb_convert_encoding($tmp['parking_id'], 'gb2312', 'utf-8');
                $tmp['price'] = $val['price'] ? $val['price'] . '萬元' : '';//價格
                $tmp['price'] = mb_convert_encoding($tmp['price'], 'gb2312', 'utf-8');
                $tmp['favorite_num'] = $val['favorite_num'];//關注車位人數
                $tmp['create_time'] = $val['create_time'] ? date('Y-m-d H:i:s', $val['create_time']) : '-';//添加時間

                fputcsv($fp, $tmp);
                unset($tmp);
                ob_flush();
                flush();
            }
        }
        fclose($fp);
        exit();

  導出數據時,留意中文的編碼格式,不然導出的中文就是亂碼。

  代碼不整潔,僅供記錄參考,哈哈。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章