Skip to content
Advertisement

php write csv to file returns blank file

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

Advertisement

Answer

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 SymfonyComponentHttpFoundationHeaderUtils;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationResponseHeaderBag;

$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);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement