php 将 csv 写入文件 returns 空白文件

php write csv to file returns blank file

我有一些如下所示的 csv 数据:

$data = 'email,score
    john@do.com,3
    test@test.com,4';

当我尝试将此 csv 导出到这样的文件时:

    $response = new StreamedResponse();
    $response->setCallback(
        static function () use ($data): void {
            $fp = fopen('php://output', 'wb');
            file_put_contents('exportk.csv', $data);
            fclose($fp);
        }
    );

    $response->setStatusCode(200);
    $response->headers->set('Content-Type', 'text/csv; charset=utf-8');
    $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');

我得到一个空文件,我做错了什么

来自 Symfony 文档:

https://symfony.com/doc/current/components/http_foundation.html#request

If you just created the file during this same request, the file may be sent without any content. This may be due to cached file stats that return zero for the size of the file. To fix this issue, call clearstatcache(true, $file) with the path to the binary file.

如果这不能解决问题,也许可以尝试这样的操作:

use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

$data = <<<END
email,score
john@do.com,3
test@test.com,4
END;

// Just write the file here to save to the file system if you want...

$response = new Response($data);

$disposition = HeaderUtils::makeDisposition(
    HeaderUtils::DISPOSITION_ATTACHMENT,
    'export.csv'
);

$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition', $disposition);