Created
June 7, 2016 12:55
-
-
Save rossriley/928162e5dc3d3a952a1aa4143f0ac1c6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
namespace Myapp\Response; | |
use Symfony\Component\HttpFoundation\Response; | |
class CsvResponse extends Response | |
{ | |
protected $data; | |
protected $filename = 'export.csv'; | |
public function __construct($data = array(), $status = 200, $headers = array()) | |
{ | |
parent::__construct('', $status, $headers); | |
$this->setData($data); | |
} | |
public function setData(array $data) | |
{ | |
$output = fopen('php://temp', 'r+'); | |
foreach ($data as $row) { | |
fputcsv($output, $row); | |
} | |
rewind($output); | |
$this->data = ''; | |
while ($line = fgets($output)) { | |
$this->data .= $line; | |
} | |
$this->data .= fgets($output); | |
return $this->update(); | |
} | |
public function getFilename() | |
{ | |
return $this->filename; | |
} | |
public function setFilename($filename) | |
{ | |
$this->filename = $filename; | |
return $this->update(); | |
} | |
protected function update() | |
{ | |
$this->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $this->filename)); | |
if (!$this->headers->has('Content-Type')) { | |
$this->headers->set('Content-Type', 'text/csv'); | |
} | |
return $this->setContent($this->data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment