Created
March 25, 2014 02:36
-
-
Save coreymcmahon/9754295 to your computer and use it in GitHub Desktop.
Custom Response facade for additional response types in Laravel 4
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 Acme\Extensions\Facades; | |
class Response extends \Illuminate\Support\Facades\Response | |
{ | |
public static function csv($data, $filename = 'data.csv', $status = 200, $delimiter = "|", $linebreak = "\n", $headers = array()) | |
{ | |
return static::stream(function () use ($data, $delimiter, $linebreak) { | |
foreach ($data as $row) { | |
$keys = array(); $values = array(); | |
$i = (isset($i)) ? $i+1 : 0; | |
foreach ($row as $k => $v) { | |
if (!$i) $keys[] = is_string($k) ? '"' . str_replace('"', '""', $k) . '"' : $k; | |
$values[] = is_string($v) ? '"' . str_replace('"', '""', $v) . '"' : $v; | |
} | |
if (count($keys) > 0) echo implode($delimiter, $keys) . $linebreak; | |
if (count($values) > 0) echo implode($delimiter, $values) . $linebreak; | |
} | |
}, 200, array_merge(array( | |
'Content-type' => 'application/csv', | |
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', | |
'Content-Description' => 'File Transfer', | |
'Content-type' => 'text/csv', | |
'Content-Disposition' => 'attachment; filename=' . $filename, | |
'Expires' => '0', | |
'Pragma' => 'public', | |
), $headers)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment