Skip to content

Instantly share code, notes, and snippets.

@jewei
Created October 18, 2019 03:11
Show Gist options
  • Save jewei/a62c1d4fbde8c2359d22aff520742f90 to your computer and use it in GitHub Desktop.
Save jewei/a62c1d4fbde8c2359d22aff520742f90 to your computer and use it in GitHub Desktop.
<?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