我如何设置utf-8到php的csv文件

public function ExportCSV(){ $this->load->dbutil(); $this->load->helper('file'); $this->load->helper('download'); $delimiter = ","; $newline = "\r\n"; $slash = "∕"; $filename = "testnaja.csv"; $query = "select * from student where room_id = 011"; $result = $this->db->query($query); $data = $this->dbutil->csv_from_result($result, $delimiter, $newline); force_download($filename, $data); } 

我想生成excel文件从我的表中导出数据到它。
.xls和.csv中的输出

在csv输出是:

在这里输入图像说明

请帮忙。 谢谢。

改变你的force_download

 force_download($filename, $data); 

对此:

 force_download($filename, "\xEF\xBB\xBF" . $data); 

这使得输出的UTF-8 + BOM能够被MS Excel识别

我不知道我是否正确理解了你,但是如果你的问题是你想让Excel识别你的CSV文件为UTF-8编码,那么你必须在文件中添加一个UTF-8 BOM 。 只需在您的CSV输出上添加

 chr(239) . chr(187) . chr(191) // xEF xBB xBF 

例如:

 $data = chr(239) . chr(187) . chr(191) . $this->dbutil->csv_from_result($result, $delimiter, $newline); 

如果您的问题是关于强制下载,也许https://stackoverflow.com/a/33593363/11354会帮助。

要设置codeigniter以下载CSV格式,请使用以下代码。

 function _push_file($path, $name) { // make sure it's a file before doing anything! if(is_file($path)) { // required for IE if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } // get the file mime type using the file extension $this->load->helper('file'); $mime = get_mime_by_extension($path); // Build the headers to push out the file properly. header('Pragma: public'); // required header('Expires: 0'); // no cache header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Last-Modified: '.gmdate ('D, d MYH:i:s', filemtime ($path)).' GMT'); header('Cache-Control: private',false); header('Content-Type: '.$mime); // Add the mime type from Code igniter. header('Content-Disposition: attachment; filename="'.basename($name).'"'); // Add the file name header('Content-Transfer-Encoding: binary'); header('Content-Length: '.filesize($path)); // provide file size header('Connection: close'); readfile($path); // push it out exit(); } 

重复: Codeigniter强制下载文件

也来自: 从codeigniter mysql下载csv