Skip to content

Instantly share code, notes, and snippets.

@milo
Last active June 25, 2018 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milo/a0ec85d69512806790134c594447a0cc to your computer and use it in GitHub Desktop.
Save milo/a0ec85d69512806790134c594447a0cc to your computer and use it in GitHub Desktop.
CSV response for Nette Application
<?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