11/08/2018, 20:53

Cách download CSV trong framework Fuelphp

Download CSV cho framework Fuelphp http://fuelphp.com/ Tạo file app/classes/format.php <?php // app/classes/format.php を作成 class Format extends FuelCoreFormat { /** * CSV出力をSJIS-WINで返す * @access public * @param mixed $data * @return ...

Download CSV cho framework Fuelphp http://fuelphp.com/

Tạo file app/classes/format.php

    <?php
    // app/classes/format.php を作成
    class Format extends FuelCoreFormat {
         /**
         * 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;
        }
    }

Đăng ký class vừa tạo vào bootstrap

<?php
    // 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',
    ));

Tạo function thực hiện việc donwload

      public static function export_csv($array, $csv_name) {
      // Response
      $response = new Response();

      // content-type: csv
      $response->set_header('Content-Type', 'application/csv');

      // ファイル名をセット
      $response->set_header('Content-Disposition', 'attachment; filename="'. $csv_name .'"');

      // キャッシュをなしに
      $response->set_header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate');
      $response->set_header('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT');
      $response->set_header('Pragma', 'no-cache');

      // CSVを出力
      echo Format::forge($array)->to_csv();

      // Response
      return $response->send(true);
    }
0