Help us understand the problem. What is going on with this article?

FuelPHPでCSVの出力

More than 5 years have passed since last update.

英語圏には無縁の問題として、
日本で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;
}

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした