Laravel9 response()->stream() 使用 fwrite() 得到空结果

问题描述 投票:0回答:1

我需要将大量数据导出为 CSV 字符串。 所以我尝试将 fopen('php://stdout', w) 与 fwrite($file, $data) 一起使用。 但 Laravel response()->stream() 不会返回任何内容,也不会出现错误。 我有谁的版本。第一个是 fwrite(),第二个是 php8 产量。 有人可以向我解释一下问题是什么吗?

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);
}
stream stdout laravel-9 fwrite yield
1个回答
0
投票

也许可以尝试使用

php://output
而不是
php://stdout

$output = fopen('php://output', 'w');
© www.soinside.com 2019 - 2024. All rights reserved.