fputcsv 导出excel,解决内存、性能、乱码、科学计数法问题

来源:https://blog.51cto.com/12750968/2133076

记录作为后续使用

 

<?php 
ob_end_clean();

// 文件名
$filename = $type.'_order_'.date('YmdHis').'.csv';
$title = ['单号', '状态', '数量', '商品名', '发货人', '收货人'];

// 设置 header 头
header('Content-Type: application/vnd.ms-excel'); // 文件格式
header('Content-Type: charset=utf-8'); // 文件编码
header('Content-Disposition: attachment; filenaeme='. $filename); // 文件名
header('Content-Type: application/octet-stream'); // 二进制流
// header("Accept-Ranges:bytes");// 表明范围单位为字节,可不写
header("Pragma: no-cache"); // 禁止缓存
header("Expires: 0");// 有效期时间

$fp = fopen('php://output','w+');

fputcsv($fp, transCode($title));

// 处理数据 [伪代码]
// 如果从数据库获取数据并处理,可以分批进行查询,也可以使用多个文件进行导出
// $result

$count = 0; //计数器
$limit = 10000; 

while ($row = $result->fetchRow()) {
    $count++;
    if ($count == $limit) {
        ob_flush(); // 刷新 php 缓存
        flush(); // 刷新输出缓存
        $count = 0; // 重置计数器
    }

    // 逐行写入
    fputcsv($fp, transCode($row));
    unset($row);
}

fclose($fp);
// 编码转换
// 代码一般是 utf-8 格式, csv 导出默认也是 utf-8 格式,而 excel 直接打开默认不识别 utf-8 格式,因此,要导出数据都要进行 格式转换
// 每个字段后加上 "t" 可以防止长数字显示为科学计数法 
function transCode(array &$arr){
    foreach ($arr as &$v) {
        $v = "t".iconv('utf-8', 'gb2312//ignore', $v);
    }
}

可能出现问题:
乱码问题:转换编码为 gb2312 或 gbk
特殊字符问题:字段后 加 “t” 或 双引号
数据丢失问题:gb2312 可识别的字符比较少,可以换成 gbk
csv 时间格式筛选: 文本格式的时间无法进行分组筛选,可在 转码的时候进行过滤,如果是时间格式,不转成 文本格式,即 不加 “t”

 

 

 

 

 


Fatal error: Uncaught Error: Call to undefined function create_function() in /www/wwwroot/www.menglei.net/wp-content/plugins/autoptimize/classes/autoptimizeStyles.php:96 Stack trace: #0 /www/wwwroot/www.menglei.net/wp-content/plugins/autoptimize/autoptimize.php(293): autoptimizeStyles->read() #1 [internal function]: autoptimize_end_buffering() #2 /www/wwwroot/www.menglei.net/wp-includes/functions.php(5373): ob_end_flush() #3 /www/wwwroot/www.menglei.net/wp-includes/class-wp-hook.php(324): wp_ob_end_flush_all() #4 /www/wwwroot/www.menglei.net/wp-includes/class-wp-hook.php(348): WP_Hook->apply_filters() #5 /www/wwwroot/www.menglei.net/wp-includes/plugin.php(517): WP_Hook->do_action() #6 /www/wwwroot/www.menglei.net/wp-includes/load.php(1260): do_action() #7 [internal function]: shutdown_action_hook() #8 {main} thrown in /www/wwwroot/www.menglei.net/wp-content/plugins/autoptimize/classes/autoptimizeStyles.php on line 96