Last active
October 28, 2024 06:45
-
-
Save mpijierro/2aae202292223292ee660ea76bbef871 to your computer and use it in GitHub Desktop.
Example streaming large CSV files with Laravel and thousands of queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Src\Csv; | |
use Illuminate\Http\Response; | |
use Symfony\Component\HttpFoundation\StreamedResponse; | |
/** | |
* Class DownloadLargeCsv | |
* | |
* @package Src\Csv | |
* | |
* This class set streaming large csv chunking queries | |
* | |
*/ | |
class DownloadLargeCsv | |
{ | |
const SIZE_CHUNK = 200; | |
const DOWNNLOAD_NAME = 'filename_example.csv'; | |
private $fileHandle; | |
public function execute() | |
{ | |
return new StreamedResponse(function () { | |
$this->openFile(); | |
$this->addBomUtf8(); | |
$this->addContentHeaderInFile(); | |
$this->processUsers(); | |
$this->closeFile(); | |
}, Response::HTTP_OK, $this->headers()); | |
} | |
private function openFile() | |
{ | |
$this->fileHandle = fopen('php://output', 'w'); | |
} | |
private function addBomUTf8 (){ | |
fwrite($this->fileHandle, $bom = (chr(0xEF).chr(0xBB).chr(0xBF))); | |
} | |
private function addContentHeaderInFile() | |
{ | |
$this->putRowInCsv([ | |
'Example header 1', | |
'Example header 2', | |
'Example header 3' | |
]); | |
} | |
private function processUsers() | |
{ | |
User::with(['posts'])->chunk(self::SIZE_CHUNK, function ($users) { | |
foreach ($users as $user) { | |
$this->addUserLine($user); | |
} | |
}); | |
} | |
private function addUserLine(User $user) | |
{ | |
$this->putRowInCsv([ $user->exampleContent1(), | |
$user->exampleContent2(), | |
$user->exampleContent3() | |
]); | |
} | |
private function putRowInCsv (array $data){ | |
fputcsv($this->fileHandle, $data, ';'); | |
} | |
private function closeFile() | |
{ | |
fclose($this->fileHandle); | |
} | |
private function headers() | |
{ | |
return [ | |
'Content-Type' => 'text/csv', | |
'Content-Disposition' => 'attachment; filename="'.self::DOWNNLOAD_NAME.'"', | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you