issei-m/streamed-csv-response

Extends the Symfony\Component\HttpFoundation\StreamedResponse to send a CSV file to client.

v1.1 2017-05-16 15:38 UTC

This package is auto-updated.

Last update: 2024-03-05 07:32:50 UTC


README

SensioLabsInsight

Build Status Scrutinizer Code Quality Code Coverage License

Extending the Symfony\Component\HttpFoundation\StreamedResponse to send a CSV file to client. It works with Symfony 2.7 and newer (including 3 and 4 of course) on PHP 7.x.

Usage

Very easy, just pass two arguments to the constructor. For instance in Symfony's controller:

public function exportCustomersAction(Request $request)
{
    return new StreamedCsvResponse(
        // 1st parameter: any iterable CSV rows
        (function () {
            yield ['Full Name', 'Email', 'Gender'];

            foreach ($this->get('user_repository')->getAllUsers() as $user) {
                yield [
                    $user->getFullName(),
                    $user->getEmail(),
                    $user->getGender(),
                ];
            }

            // Of course, you can also use any iterable for cell representation
            yield (function () {
                yield '村澤 逸生';
                yield 'issei.m7@gmail.com';
                yield '男性';
            })();
        })(),

        // 2nd parameter: the filename the browser uses in downloading 
        'customers.csv'
    ); 
}

auto encoding

If the response has been set any charset, every cell content will be encoded accordingly when sending:

$response = new StreamedCsvResponse($rows, 'customers.csv');
$response->setCharset('SJIS-win');

$response->send(); // Every cells are automatically encoded to SJIS-win.

Installation

Use Composer to install the package:

$ composer require issei-m/streamed-csv-response