Last active
December 15, 2016 06:46
-
-
Save EITANINOMIYA/edf53d948a0bb0889c5049ec91923bd2 to your computer and use it in GitHub Desktop.
【PHP】csv生成&ダウンロード
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
/*################################################# | |
# エクセルで開いた際に文字化けしないようにエンコードしてcsvを生成 | |
#################################################*/ | |
<?php | |
// ファイル名 | |
$file_path = "tmp_".date('Ymd').".csv"; | |
// ------------------------------ | |
// csv生成 | |
// ------------------------------ | |
// CSVに出力するタイトル行 | |
$title_s = array("No.","タイトル","内容"); | |
// CSVに出力する内容 | |
$body_s = array( | |
array('no' => 1, 'title' => 'タイトル1', 'body' => '内容1'), | |
array('no' => 2, 'title' => 'タイトル2', 'body' => '内容2'), | |
array('no' => 3, 'title' => 'タイトル3', 'body' => '内容3'), | |
array('no' => 4, 'title' => 'タイトル4', 'body' => '内容4'), | |
array('no' => 5, 'title' => 'タイトル5', 'body' => '内容5') | |
); | |
if( touch($file_path) ){ | |
// オブジェクト生成 | |
$file = new SplFileObject( $file_path, "w" ); | |
// タイトル行のエンコードをSJIS-winに変換(一部環境依存文字に対応用) | |
$header_s = array(); | |
foreach( $title_s as $key => $val ){ | |
$header_s[] = mb_convert_encoding($val, 'SJIS-win', 'UTF-8'); | |
} | |
// エンコードしたタイトル行を配列ごとCSVデータ化 | |
$file->fputcsv($header_s); | |
foreach($body_s as $value) { | |
$csv = [ | |
$value['no'], $value['title'], $value['body'] | |
]; | |
foreach($csv as $key => $val) { | |
$csv[$key] = mb_convert_encoding($val, 'SJIS-win', 'UTF-8'); | |
} | |
$file->fputcsv($csv); | |
} | |
} else { | |
die('file touch error'); | |
} | |
// ------------------------------ | |
// csvダウンロード | |
// ------------------------------ | |
header("Pragma: public"); | |
header("Expires: 0"); | |
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); | |
header("Cache-Control: private",false); | |
header("Content-Type: application/force-download"); | |
header('Content-Disposition: attachment; filename='.basename($file_path).';'); | |
header("Content-Transfer-Encoding: binary"); | |
readfile("$file_path"); | |
exit; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment