Skip to content

Instantly share code, notes, and snippets.

@tkuchiki
Created July 18, 2013 03:28
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 tkuchiki/6026507 to your computer and use it in GitHub Desktop.
Save tkuchiki/6026507 to your computer and use it in GitHub Desktop.
Excel 対応 CSV download
<?php
/*
* How to use:
*
* $str = Csv::array_to_csv_str($csv_rows);
* $str = Csv::convert_encoding($str);
* Csv::download($str, 'filename');
*/
class Csv
{
static public function quote($str)
{
if (mb_strpos($str, '"') !== false) {
$str = str_replace('"', '""', $str);
}
return '"' . $str . '"';
}
static public function array_to_csv_str($csv_data, $newline = "\r\n")
{
$line = '';
foreach ($csv_data as $row) {
$line .= implode(',', array_map(array('Csv', 'quote'), $row)) . $newline;
}
return $line;
}
static public function convert_encoding($str, $to_encoding = 'SJIS', $from_encoding = 'UTF-8')
{
return mb_convert_encoding($str, $to_encoding, $from_encoding);
}
static public function download($str, $filename, $ext = '.csv')
{
$filename .= $ext;
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $filename);
echo $str;
exit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment