這是問題 我想將我的數據轉換爲csv格式並下載它。一切都很好,直到我已經下載的csv文件,並且在文件的第一行會有一個空格的文件上有一個小錯誤。Codeigniter強制下載CSV文件錯誤
例如 力下載
"name","age",
"brad pit","40",`
力下載
"name","age",
"brad pit","40",
,我已經下載CSV文件之前和之後我嘗試打開智慧我的Excel中會出現類似這樣的
「名稱「| age
brad pit | 40
我相信這是因爲我下載的csv文件在數據的第一行出現了外部空間線。
下面的代碼)force_download的
//write csv data $data = $this->dbutil->csv_from_result($query, $delimiter); //create random file name $name = rand().'_salesperson_data_'.date('d-m-y').'.csv'; if (! write_file('./csv/'.$name, $data)) { echo 'Unable to write the CSV file'; } else { //perform download $file = file_get_contents("./csv/".$name); // Read the file's contents $filename = 'salesperson_data_'.date('d-m-y').'.csv'; force_download($filename, $file); }
源(
if (! function_exists('force_download')) { function force_download($filename = '', $data = '') { if ($filename == '' OR $data == '') { return FALSE; } // Try to determine if the filename includes a file extension. // We need it in order to set the MIME type if (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 it if (! isset($mimes[$extension])) { $mime = 'application/octet-stream'; } else { $mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension]; } // Generate the server headers if (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)); } 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); } }
我認爲TRIM將是我最後的解決方案,我試圖把任何地方可行,但還是老樣子相同。我找不到解決這個問題的辦法。請幫忙。這卡住了我已經2天了。
謝謝先進。
請向我們展示force_download()方法的來源? – phirschybar 2011-05-18 14:03:09
我剛剛加入。thx – 2011-05-18 15:42:10
運行查詢後執行: print_r($ query);出口; 並告訴我們你得到了什麼? – phirschybar 2011-05-18 18:53:14