CSV导出大量数据

$csvname = $csvname . '.csv';
header('Content-Type: application/vnd.ms-excel;charset=GB2312');
header('Content-Disposition: attachment;filename="' . $csvname . '"');
header('Cache-Control: max-age=0');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache, must-revalidate'); //HTTP/1.1
//open handle,php://output 表示直接输出到浏览器
$fp = fopen('php://output', 'a');

//output csv first column
$head = $columName;
foreach ($head as $i => $v) {
    $head[$i] = iconv('utf-8', 'gbk', $v);
}
fputcsv($fp, $head);

// 计数器
$cnt = 0;
$limit = 2000;

// 从数据库中获取数据,节省内存,从句柄中一行一行读即可
$i = 2;

foreach ($result as $key => $val) {
    $cnt++;
    //每隔$limit行,刷新一下输出buffer
    if ($limit == $cnt) {
        ob_flush();
        flush();
        $cnt = 0;
    }

    $rows[$i] = iconv('utf-8', 'gbk', $val['vendor_item']);
    $rows[$i + 1] = iconv('utf-8', 'gbk', $val['item_code']);
    $rows[$i + 2] = iconv('utf-8', 'gbk', $val['product_name']);
    $rows[$i + 3] = iconv('utf-8', 'gbk', $val['brand_code']);
    $rows[$i + 4] = iconv('utf-8', 'gbk', $val['brand']);
    $rows[$i + 5] = iconv('utf-8', 'gbk', $val['vendor_id']);
    $rows[$i + 6] = iconv('utf-8', 'gbk', $val['vendor_name']);
    $rows[$i + 7] = iconv('utf-8', 'gbk', $val['warehouse_code']);
    $rows[$i + 8] = iconv('utf-8', 'gbk', $val['quantity']);
    $rows[$i + 9] = iconv('utf-8', 'gbk', $val['lockcount']);
    $rows[$i + 10] = iconv('utf-8', 'gbk', $val['bindcount']);
    fputcsv($fp, $rows);
    //释放数组
    unset($rows);
}

 

转载于:https://www.cnblogs.com/gide/p/4449764.html

你可能感兴趣的:(CSV导出大量数据)