123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- <?php
- namespace huolib\tool;
- use ZipArchive;
- class Export {
- const MAX_ROWS = 10000;
- public static function ins() {
- return new static();
- }
-
- public static function exportCsv($head, $data, $path = '', $file_name = "", $extend = '.csv', $is_output = false) {
- if (empty($path)) {
- $_root_path = RUNTIME_PATH.'export';
- } else {
- $_root_path = RUNTIME_PATH.'export'.DS.$path;
- }
- if (!is_dir($_root_path)) {
- @mkdir($_root_path, 0755, true);
- }
- set_time_limit(0);
- if (empty($file_name)) {
- $_file_name = date('YmdHi', time()).$extend;
- } else {
- $_file_name = $file_name.$extend;
- }
- $_limit = self::MAX_ROWS;
- $_cnt = 0;
- $_file_path = $_root_path.DS.$_file_name;
- $_file_path = iconv('UTF-8', 'GBK', $_file_path);
-
- $_fp = fopen($_file_path, 'w');
-
- if (!empty($head)) {
- foreach ($head as $_key => $_val) {
- $head[$_key] = iconv('utf-8', 'gbk', $_val);
- }
- fputcsv($_fp, $head);
- }
- foreach ($data as $_row) {
- $_cnt++;
- if ($_limit == $_cnt) {
-
- ob_flush();
- flush();
- $_cnt = 0;
- }
- foreach ($_row as $_key => $_val) {
- $_row[$_key] = iconv('utf-8', 'gbk//IGNORE', $_val);
- }
- fputcsv($_fp, $_row);
- }
- fclose($_fp);
- if ($is_output) {
-
- header('Content-Type: application/vnd.ms-excel;charset=utf-8');
- header('Content-Disposition: attachment;filename="'.$_file_name.'"');
- header('Cache-Control: max-age=0');
- @readfile($_file_path);
- exit;
- }
- }
-
- public static function exportZip($file_name_arr, $path = '', $mark) {
- if (empty($file_name_arr)) {
- return;
- }
- if (empty($path)) {
- $_root_path = RUNTIME_PATH.'export';
- } else {
- $_root_path = RUNTIME_PATH.'export'.DS.$path;
- }
- if (!is_dir($_root_path)) {
- @mkdir($_root_path, 0755, true);
- }
-
- $_zip_class = new ZipArchive();
- $_file_name = $mark.".zip";
- $_file_path = $_root_path.DS.$_file_name;
- $_file_path = iconv('UTF-8', 'GBK', $_file_path);
- $_zip_class->open($_file_path, ZipArchive::CREATE);
- foreach ($file_name_arr as $file) {
- $_basename = $file;
- $file = $_root_path.DS.$file;
- $file = iconv('UTF-8', 'GBK', $file);
- $_zip_class->addFile($file, $_basename);
- }
- $_zip_class->close();
-
- header("Cache-Control: max-age=0");
- header("Content-Description: File Transfer");
- header('Content-disposition: attachment; filename='.$_file_name);
- header("Content-Type: application/zip");
- header("Content-Transfer-Encoding: binary");
- header('Content-Length: '.filesize($_file_path));
- @readfile($_file_path);
- @unlink($_file_path);
- exit;
- }
- }
|