Last active
June 25, 2018 12:06
-
-
Save milo/a0ec85d69512806790134c594447a0cc to your computer and use it in GitHub Desktop.
CSV response for Nette Application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\Responses; | |
use Nette\Application; | |
use Nette\Http; | |
class CsvResponse implements Application\IResponse | |
{ | |
/** @var string */ | |
private $fileName; | |
/** @var string */ | |
private $delimiter; | |
/** @var iterable */ | |
private $rows; | |
/** @var array */ | |
private $columnTitles; | |
/** | |
* @param string $fileName file name displayed by browser, extension should be .csv | |
* @param string $delimiter columns delimiter (comma, semicolon...) | |
* @param iterable $rows | |
* @param array $columnTitles first line values | |
*/ | |
public function __construct(string $fileName, string $delimiter, iterable $rows, array $columnTitles = []) | |
{ | |
$this->fileName = $fileName; | |
$this->delimiter = $delimiter; | |
$this->rows = $rows; | |
$this->columnTitles = $columnTitles; | |
} | |
public function send(Http\IRequest $httpRequest, Http\IResponse $httpResponse) | |
{ | |
$httpResponse->setContentType('text/csv', 'utf-8'); | |
$httpResponse->setHeader('Content-Description', 'File Transfer'); | |
$httpResponse->setHeader( | |
'Content-Disposition', | |
'attachment; filename="' . str_replace('"', "'", $this->fileName) . '"; filename*=utf-8\'\'' . rawurlencode($this->fileName) | |
); | |
$fd = fopen('php://output', 'wb'); | |
if (count($this->columnTitles) || count($this->rows)) { # With no rows, MS Excel shows BOM in A1 cell. | |
# Send BOM, otherwise MS Excel expects data in local OS encoding (e.g. Windows-1250) | |
fputs($fd, "\xEF\xBB\xBF"); | |
} | |
if (count($this->columnTitles)) { | |
fputcsv($fd, $this->columnTitles, $this->delimiter); | |
} | |
foreach ($this->rows as $row) { | |
fputcsv($fd, $row instanceof \Traversable ? iterator_to_array($row) : (array) $row, $this->delimiter); | |
} | |
fclose($fd); | |
die(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment