Example 1: Simply export a few pieces of data
public function exportData()
{
$once = 5;
$file_name = date('Ymd').'.csv';
$url = storage_path('/app/'. $file_name); //保存路径
$header = [ //表头
'ID',
'NAME'
];
$data = [ //导出的数据
['id'=> 1, 'name'=> '小王'],
['id'=> 2, 'name'=> '小李'],
['id'=> 3, 'name'=> '小王'],
['id'=> 4, 'name'=> '小李'],
['id'=> 5, 'name'=> '小王'],
['id'=> 6, 'name'=> '小李'],
['id'=> 7, 'name'=> '小王'],
['id'=> 8, 'name'=> '小李'],
['id'=> 9, 'name'=> '小王'],
['id'=> 10, 'name'=> '小李'],
['id'=> 11, 'name'=> '小王'],
['id'=> 12, 'name'=> '小李'],
];
$fp = fopen($url, "a");
fputcsv($fp, $header);
fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF)); // 添加 BOM
$lists = array_chunk($data, $once); // 数据分块
foreach ($lists as $key=>$list){
foreach ($list as $item) {
fputcsv($fp, $item);
}
unset($lists[$key]);
}
fclose($fp);
}
Example 2: Look up the table and export 20W pieces of data (the local experimental single table queries 3 fields, and it takes about ten seconds to export 20W pieces)
public function exportData()
{
set_time_limit(0);
$page_size = 10000; //单次查询数量
$file_name = date('Ymd').'.csv'; //文件名称
$url = storage_path('/app/'. $file_name); //保存路径
$header = [ //表头
'ID', '订单号', '创建时间'
];
$field = [ //对应字段
'id', 'order_id', 'create_time'
];
$fp = fopen($url, "a");
fputcsv($fp, $header);
fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF)); // 添加 BOM
$where = [ //查询条件
['id', '<', 200000],
];
$index = 1;
$list = $this->getData($where,$page_size,$index,$field);
while(!empty($list)){
$list = $this->getData($where,$page_size,$index,$field);
foreach ($list as $item) {
fputcsv($fp, (array)$item);
}
$index ++;
if($index%10 === 0){
//防止卡死
sleep(1);
}
}
fclose($fp);
}
function getData($where, $page_size, $index, $field)
{
$data = DB::table('order')->where($where)
->select($field)
->forPage($index, $page_size)
->get()->toArray();
//todo 处理数据
return $data;
}
If you only export table data, you don't need to process the data, you can use chunk() in laravel, like this:
$fp = fopen('xxx.csv', 'a');
Model::->orderBy('id')->chunk(1000, function($items) use ($fp) {
foreach ($items as $item) {
fputcsv($fp, $item);
}
});
fclose($fp);