利用php CI force_download($filename, $data) 下載.csv 檔案解決檔案名稱亂碼,檔案內容亂碼

來源:互聯網
上載者:User
利用php CI force_download($filename, $data) 下載.csv 檔案解決檔案名稱亂碼,檔案內容亂碼。做了很久終於知道了很好的解決方案。

1.載入輔助函數

$this->load->helper('download');  //下載輔助函數$this->load->helper('string');    //字元編碼轉換輔助翻書

2.force_download($filename, $data)通過它的代碼可以知道$data 必須是字串,如果不是字串會出錯的。是數組,必須轉換成字串,用函數implode即可,該函數用法見官網,更具我的項目代碼如下。

public function download() {      // 輸出Excel檔案頭     //解決IE,firework等瀏覽器檔案名稱亂碼問題$filename = '已拆回款資料.csv';$newarray=array();該結果是一個二維數組if ($this->input->get () !== false) {$conn = $this->getformdata ();}// 輸出Excel列名資訊$head = array ('ID','回款號','回款金額(分)','調整渠道成本','回款時間','匯入SO時間','渠道名稱','合約ID' );foreach ( $head as $i => $v ) {// CSV的Excel支援GBK編碼,一定要轉換,否則亂碼 $head [$i] = utf2gbk($v);}$newarray[]=implode(',',$head);$sql = "select * from sinapay_boss_income where {$conn} order by income_status asc, boss_income_id desc";$query = $this->db->query ( $sql );// 計數器$cnt = 0;// 每隔$limit行,重新整理一下輸出buffer,不要太大,也不要太小$limit = 8000;foreach ( $query->result_array () as $row ) {$cnt ++;if ($limit == $cnt) { // 重新整理一下輸出buffer,防止由於資料過多造成問題ob_flush ();flush ();$cnt = 0;}// 讀取表資料$content = array ();$content [] =$row ['boss_income_id'];$content [] =$row ['income_num'];$content [] =$row ['income_amount'];$content [] =$row ['modified_cost'];$content [] =$row ['income_date'];$content [] =$row ['write_so_month'];$content [] =utf2gbk($row ['channel_name']);$content [] =utf2gbk($row ['income_contract_id']);$newarray[]=implode(',',$content);}$newarray=implode("\n",$newarray);force_download($filename, $newarray); }} 

3.測試後我發現ie瀏覽器檔案名稱是亂碼,firefox 瀏覽器檔案名稱也是亂碼。於是對輔助函數做了以下的修改,以下加了背景顏色的代碼是我添加的。

if ( ! function_exists('force_download')){function force_download($filename = '', $data = ''){if ($filename == '' OR $data == ''){return FALSE;}//ie 瀏覽器解決檔案名稱是亂碼$filename = urlencode($filename);               $filename = str_replace("+", "%20", $filename);// Try to determine if the filename includes a file extension.// We need it in order to set the MIME typeif (FALSE === strpos($filename, '.')){return FALSE;}// Grab the file extension$x = explode('.', $filename);$extension = end($x);// Load the mime types@include(APPPATH.'config/mimes'.EXT);// Set a default mime if we can't find itif ( ! isset($mimes[$extension])){$mime = 'application/octet-stream';}else{$mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];}// Generate the server headersif (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")){header('Content-Type: "'.$mime.'"');header('Content-Disposition: attachment; filename="'.$filename.'"');header('Expires: 0');header('Cache-Control: must-revalidate, post-check=0, pre-check=0');header("Content-Transfer-Encoding: binary");header('Pragma: public');header("Content-Length: ".strlen($data));}elseif(strstr($_SERVER['HTTP_USER_AGENT'], "Firefox")){   //解決firefox 檔案名稱亂碼header('Content-Type: "'.$mime.'"');header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"');header('Expires: 0');header('Cache-Control: must-revalidate, post-check=0, pre-check=0');header("Content-Transfer-Encoding: binary");header('Pragma: public');header("Content-Length: ".strlen($data));}else{header('Content-Type: "'.$mime.'"');header('Content-Disposition: attachment; filename="'.$filename.'"');header("Content-Transfer-Encoding: binary");header('Expires: 0');header('Pragma: no-cache');header("Content-Length: ".strlen($data));}exit($data);}}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.