issei-m/streamed-csv-response

扩展了 Symfony\Component\HttpFoundation\StreamedResponse 来向客户端发送 CSV 文件。

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

This package is auto-updated.

Last update: 2024-09-05 08:28:30 UTC


README

SensioLabsInsight

Build Status Scrutinizer Code Quality Code Coverage License

扩展 Symfony\Component\HttpFoundation\StreamedResponse 以向客户端发送 CSV 文件。它与 Symfony 2.7 及更高版本(包括 3 和 4)兼容,运行在 PHP 7.x 上。

用法

非常简单,只需将两个参数传递给构造函数即可。例如,在 Symfony 的控制器中

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'
    ); 
}

自动编码

如果响应已设置任何 charset,则在发送时每个单元格的内容都将相应地编码

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

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

安装

使用 Composer 安装包

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