工作中,经常用到需要将大量数据导出的场景,而大数据量的导出,csv比之excel速度更快,文件更小,更满足需求。
以下是一个csv文件导出类,综合考虑了系统内存,文件格式等各类问题
class Csv
{
private static $_instance = NULL;
private static $_pointer = null;
private function __construct()
{
}
public static function getInstance() {
if (is_null(self::$_instance)) {
self::$_instance = new Csv();
}
return self::$_instance;
}
private function __clone()
{
// TODO: Implement __clone() method.
}
public static function initCsv($filename, $head) {
ob_clean();
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '.csv"'); //指定下载文件的描述
header("Content-Type: application/force-download");
// 添加bom头,避免excel打开文件乱码
$bom = pack("H*", 'EFBBBF');
self::$_pointer = fopen("php://output", "w");
fwrite(self::$_pointer, $bom);
fputcsv(self::$_pointer, $head);
}
public static function makeCsvByStep($items) {
foreach ($items as $item) {
// 长数字处理
foreach ($item as &$val) {
$val = "\t" . $val;
}
fputcsv(self::$_pointer, $item);
ob_flush();
flush();
}
}
public static function exportCsv() {
fclose(self::$_pointer);
exit;
}
}