Created
October 18, 2019 03:11
-
-
Save jewei/a62c1d4fbde8c2359d22aff520742f90 to your computer and use it in GitHub Desktop.
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 | |
class Example | |
{ | |
public function handle() | |
{ | |
$this->sendHeader('test.csv'); | |
$this->sendData(['foo', 'bar', 'foobar'], [ | |
['a', 'b', 'c'], | |
['d', 'e', 'f'], | |
['h i', 'j "k', 'l m'], | |
['"aaa"', '"bbb"'], | |
]); | |
} | |
private function sendHeader(string $filename) | |
{ | |
$filename = preg_replace("/[^a-zA-Z0-9.-]+/", "", $filename); | |
header('Content-Type: text/csv'); | |
header('Content-Transfer-Encoding: binary'); | |
header('Content-Description: File Transfer'); | |
header('Content-Disposition: attachment; filename="'.$filename .'"'); | |
} | |
private function sendData(array $headers, array $rows) | |
{ | |
$handle = fopen('php://output', 'w'); | |
fputcsv($handle, $headers); | |
foreach($rows as $row) { | |
fputcsv($handle, $row); | |
} | |
fclose($handle); | |
die(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment