Created
July 18, 2013 03:28
-
-
Save tkuchiki/6026507 to your computer and use it in GitHub Desktop.
Excel 対応 CSV download
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 | |
/* | |
* 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