簡単にCSVダウンロードが可能になるCSVヘルパーの作成方法をまとめます。
ここに貼ってあるコードは僕のgithubからダウンロード出来ます。
>> cakephp-csv-helper – github
それでは使い方を紹介します。
まずはCsvHelper.phpを作成しましょう。
app/View/Helper 以下に CsvHelper.phpとして以下のコードをコピペしましょう。
clear(); } function clear() { $this->line = array(); $this->buffer = fopen('php://temp/maxmemory:'.(5*1024*1024), 'r+'); } function addField($value) { $this->line[] = $value; } function endRow() { $this->addRow($this->line); $this->line = array(); } function addRow($row) { fputcsv($this->buffer, $row, $this->delimiter, $this->enclosure); } function renderHeaders() { header("Content-type:application/vnd.ms-excel"); header("Content-disposition:attachment;filename=".$this->filename); } function setFilename($filename) { $this->filename = $filename; if (strtolower(substr($this->filename, -4)) != '.csv') { $this->filename .= '.csv'; } } function render($outputHeaders = true, $to_encoding = null, $from_encoding = "auto") { if ($outputHeaders) { if (is_string($outputHeaders)) { $this->setFilename($outputHeaders); } $this->renderHeaders(); } rewind($this->buffer); $output = stream_get_contents($this->buffer); if ($to_encoding) { $output = mb_convert_encoding($output, $to_encoding, $from_encoding); } return $this->output($output); } }
コピペ出来ましたか?
次にやることとしては、CSVダウンロードを行いたいControllerでメソッドを作成します。
このときの注意としては、さきほど作った CsvHelper.php を先頭で読み込んでおきましょう。
※ここでは UsersController.php としてファイルを作成しています。
layout = false; $filename = 'Csvダウンロード_'.date('YmdHis'); $genders = array('1' => '男性', '2' => '女性'); // 表の一行目を作成 $th = array('id', 'username', 'gender', 'status'); // 表の内容を取得 $td = $this->User->find('all', array('fields' => $th)); $this->set(compact('filename', 'genders', 'th', 'td')); } }
最後にビューを作成します。
app/View/Users/download_csv.ctp として保存しています。
Csv->addRow($th); foreach($td as $t) { $this->Csv->addField($t['User']); // .... 行を追加していく $this->Csv->endRow(); } $this->Csv->setFilename($filename); // 文字化けの場合は echo $this->Csv->render(true, 'sjis', 'utf-8'); echo $this->Csv->render();
これで完成です!
もしCSVファイルが文字化けしている場合は、
ビューの最後のrender()を
echo $this->Csv->render(true, 'sjis', 'utf-8');
に直すとなおります。
最後にまとめてコードをダウンロード出来るようにもう一度githubのURLを貼っておきます。
何か間違いなどありましたらpushしていただけるとありがたいです。
>> cakephp-csv-helper – github
この記事を読んでいるあなたにおすすめ!
CakePHPをやっているのであればこれは必読です!
CakePHP2 実践入門 (WEB+DB PRESS plus)
posted with amazlet at 13.06.20
安藤 祐介 岸田 健一郎 新原 雅司 市川 快 渡辺 一宏 鈴木 則夫
技術評論社
売り上げランキング: 11,668
技術評論社
売り上げランキング: 11,668
更新情報はFacebookページで!
ブログの更新、読んで役立つ他ブログの記事などを更新しています。