Create and Download CSV File on The Fly

    function download(){
        $this->check_permission('device', 'update', array('download'));

        $options = $this->request_params();
        //logg($options);

        $data = $this->device_m->get_devices($this->lang_id, $options);
        if($data === false){
            $this->failed_response(0, '無法取得訂單資料');
        }
        //logg($data);

        $file_name = 'Devices.csv';
        $file_path = FCPATH . 'uploads_temp' . DIRECTORY_SEPARATOR . $file_name;
        $file_url = base_url() . 'uploads_temp/' . $file_name . '?t=' . time();

        if(file_exists($file_path) == true){
            unlink($file_path);
        }
        $file = fopen($file_path,"w");

        $rowN = 1;
        $columnN = 0;

        $fields = $this->config->item('device_download_fields');

        $line = [];
        foreach($fields as $key => $item){
            $label = iconv('utf-8', 'big5', $item[0]);
            //if($key == 'partner_id') $label = '經銷商名稱';

            $line[] = $label;
        }
        fputcsv($file, $line);

        //Get options
        $products = $this->products_m->get_products_simple($this->lang_id);

        foreach($data as $device){
            $line = [];
            foreach($fields as $key => $item){
                $value = $device->{$key};

                if($key == 'product_id'){
                    $value = $this->options_m->option_name($device->{$key}, $products, 'title');
                }

                if($key == 'house'){
                    $value = $device->house_name;
                }

                if($key == 'status'){
                    $value = $device->status_name;
                }

                //$label = iconv('utf-8', 'big5', $value);
                $label = mb_convert_encoding($value, 'big5', 'utf-8');
                //if($key == 'partner_id') $label = '經銷商名稱';

                $value = str_replace(array("\r\n", "\n\r", "\n", "\r"), '  ', $value);
                $value = str_replace(array("\t"), ' ', $value);
                $line[] = $value;
            }

            fputcsv($file, $line);
        }

        fclose($file);
        //logg('done');

        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file_path));
        readfile($file_path);
        exit;
    }

Reference: