php write csv to file returns blank file

Viewed 59

I have some csv data that looks like this:

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

When I try to export this csv to a file like this:

    $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"');

I get an empty file, what am I doing wrong here

1 Answers

From the Symfony docs:

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.

If that doesn't fix the issue, maybe try something like this:

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);
Related