40
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FuelPHPでCSVの出力

Last updated at Posted at 2012-02-25

英語圏には無縁の問題として、
日本でCSVを出力するにはSJISでやらなければならない。Excelのせいで。

で、FuelPHPでCSVの出力には、本来RestControllerを使うと楽なんだけど、
to_csv()関数をoverrideできない罠。

処理を追っかけきれてないけど、COREPATH/classes/controller/rest.php の、
response()メソッドの中で、

$this->response->body(Format::forge($data)->{'to_'.$this->format}());

みたいにto_csv()を読んでるんだけど、
bootstrap.phpでoverrideしたFormatはこのタイミングだと死んでるぽい?よくわかんね。。。

RestController使わずにCSVを出力する事で、とりあえず回避。

format.php
<?php
// app/classes/format.php を作成
class Format extends Fuel\Core\Format {
	/**
	 * CSV出力をSJIS-WINで返す
	 * @access public
	 * @param mixed $data
	 * @return string csv(sjis-win)
	 */
	public function to_csv($data = null){
		$csv = parent::to_csv($data);
		$csv = mb_convert_encoding($csv, 'SJIS-win', 'UTF-8');
		return $csv;
	}
}
bootstrap.php
<?php
//(ry
// app/bootstrap.php の一部を修正
Autoloader::add_classes(array(
	// Add classes you want to override here
	// Example: 'View' => APPPATH.'classes/view.php',
	'Format' => APPPATH . 'classes/format.php',
));
hoge.php
<?php
//(ry
// TemplateController内での出力
public function action_hoge(){
	$data = array(0,1,2,3,4);
	//テンプレートを無効化してCSVとして出力
	$this->template = null;
	$this->response->set_header('Content-Type', 'application/csv');
	$this->response->set_header('Content-Disposition', 'attachment; filename="hoge.csv"');
	echo Format::forge($data)->to_csv();
	return;
}

デバッグやってないけどたぶん動く。

40
43
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?