How to download a CSV file with Slim 4

nauleyco

Noriko Yamamoto

Posted on March 13, 2020

How to download a CSV file with Slim 4

It's a sample code for CSV download with Slim 4.

<?php
declare(strict_types=1);

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class DownloadCsvFIle extends Action
{
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $args): ResponseInterface
    {
        $csv_file = '/path-to-the-csv-file/csvfilename.csv';

        $response = $response
            ->withHeader('Content-Type', 'application/octet-stream')
            ->withHeader('Content-Disposition', 'attachment; filename=csvfilename.csv')
            ->withAddedHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
            ->withHeader('Cache-Control', 'post-check=0, pre-check=0')
            ->withHeader('Pragma', 'no-cache')
            ->withBody((new \Slim\Psr7\Stream(fopen($csv_file, 'rb'))));

        return $response;
    }
}
Enter fullscreen mode Exit fullscreen mode

keyword: slim, slim4, psr-7, csv, download, file download, stream

💖 💪 🙅 🚩
nauleyco
Noriko Yamamoto

Posted on March 13, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related