php - How to optimize save to csv file over 700k rows - Laravel

I need to write over 700k lines to the csv file. The task should last less than 30 seconds, but it works 70 seconds. How can I optimize this process?
$users = User::all();
$callback = function () use ($users) {
$fh = fopen('php://output', 'w');
fputs($fh, "\xEF\xBB\xBF");
foreach ($users as $user) {
if ($user->writer) {
$books = $user->books;
foreach ($books as $book) {
fputcsv($fh, Arr::prepend($data, $book['name']), ';');
}
}
}
};
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: videoxxx
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.