I need to export huge amount of data as csv string. So I tried to use fopen('php://stdout', w) with fwrite($file, $data). But Laravel response()->stream() do not return anything nor error. I have two wersions. One with fwrite() second with php8 yield. Can somebody explain me please what is the problem? Here is the code.
public function returnCsv(array $arHeaders, array $arItems)
{
$headers = [
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=export.csv",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0",
];
$content = function () use ($arHeaders, $arItems) {
// Output CSV headers
yield implode(';', $arHeaders) . PHP_EOL; //using yield to keep the memory low
// Output CSV data
foreach ($arItems as $arItem) {
yield implode(';', $arItem) . PHP_EOL;
}
};
return response()->stream($content, 200, $headers);
}
protected function returnCsv2(array $dataHeaders, array $data)
{
$headers = [
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=export.csv",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0",
];
$callback = function () use ($dataHeaders, $data) {
$headersCsv = implode(';', $dataHeaders) . PHP_EOL;
$stdout = fopen('php://stdout', 'w');
Log::info($headersCsv);
fwrite($stdout, $headersCsv);
// Output CSV data
foreach ($data as $item) {
$itemArr = is_array($item) ? $item : $item->toArray();
$itemCsv = implode(';', $itemArr) . PHP_EOL;
fwrite($stdout, $itemCsv);
}
//fclose($stdout);
};
return response()->stream($callback,200, $headers);