利用PHP性能优化利器生成器 yield; 无论多少的数量都可以导出来,具体的用在laravel框架中使用如下所示:
数据库表
CREATE TABLE `shop_ercode_records` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`type_id` int(11) DEFAULT NULL,
`state` tinyint(255) DEFAULT NULL,
`addtime` datetime DEFAULT CURRENT_TIMESTAMP,
`usetime` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
namespace App\Http\Controllers\web;
use \App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class IndexControllers extends Controller
{
public function test()
{
$count = DB::table('shop_ercode_records')->count();
$mark = date('YmdHis') . "_";
$limit = 500000;
$page = 1;
$startTime = time();
$i = 0;
echo "开始时间为" . $startTime . "<br/>";
/*******************真正核心代码开始***********************/
do {
$i += $limit;
self::putCsv($page, $limit, $mark . $i);
$page++;
} while ($i < $count);
/*******************真正核心代码结束***********************/
$endTime = time();
echo "结束时间为" . $endTime . "<br/>";
echo "总共耗时为" . ($endTime - $startTime) . "<br/>";
}
static function putCsv($page, $limit, $mark)
{
set_time_limit(0);
$file_num = 0; //文件名计数器
$fileNameArr = array();
$fp = fopen($mark . '_' . $file_num . '.csv', 'w'); //生成临时文件
$fileNameArr[] = $mark . '_' . $file_num . '.csv';
fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码,防止乱码
//添加导出标题
fputcsv($fp, ['id', 'name', 'type_id', 'state', 'addtime', 'usetime']);
foreach (static::query($page, $limit) as $a) {
fputcsv($fp, $a);
}
fclose($fp); //每生成一个文件关闭
}
static function query($page, $limit)
{
$res = DB::table('shop_ercode_records')->orderBy('id')->forPage($page, $limit)->get()->toArray();
foreach ($res as $value) {
yield (array)$value;
}
}