php to excel 乱码

网上看到一个plugin用来导出excel的(http://justcoding.javaeye.com/blog/646988),但是会出现乱码的问题,设置了页面编码也会这样。

找到了原因:

http://developer.51cto.com/art/200912/167002.htm

乱码原因:客户使用的中文版Windows系统平台,而Windows平台的文件名编码为gb2312(gbk),而我们网页编码为了跟进现存潮流一般都采用utf-8(国际化)编码,这时当我们:header("Content-Disposition: inline; filename=\"" . $filename . ".xls\"")时就会出现乱码,假如你的网页编码就是gb2312那就不用考虑编码问题了。

解决办法:对$filename转码,执行:iconv('utf-8", "gb2312", $filename)。假如你的环境不支持iconv函数可以换别的函数,只要能将$filename的编码转为gbk就行。

根据这里的说法在(1),(2)处作了修改

..\system\plugins\to_excel_pi.php

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/*
* Excel library for Code Igniter applications
* Author: Derek Allard, Dark Horse Consulting, http://www.darkhorse.to/, April 2006
*/

function to_excel($query, $filename='exceloutput')
{
     
$headers = ''// just creating the var for field headers to append to below
     $data = ''// just creating the var for field data to append to below
     
     
$obj =& get_instance();
     
     
$fields = $query->field_data();
     
if ($query->num_rows() == 0) {
          
echo '<p>The table appears to have no data.</p>';
     } 
else {
          
foreach ($fields as $field) {
             
$headers .=  $field->name . "\t";
          }
     
          
foreach ($query->result() as $row) {
               
$line = '';
               
foreach($row as $value) {                                            
                    
if ((!isset($value)) OR ($value == "")) {
                         
$value = "\t";
                    } 
else {
                         
$value = str_replace('"', '""', $value);
                         
$value = '"' . $value . '"' . "\t";
                    }
                    
$line .= $value;
               }
               
$data .= trim($line)."\n";
          }
          
          
$data = str_replace("\r","",iconv("utf-8","gb2312",$data));//(1)
                         
          
header("Content-type: application/vnd.ms-excel;charset=UTF-8");//(2)
          
header("Content-Disposition: attachment; filename=$filename.xls");
          
echo "$headers\n$data";  
     }
}
?>

 

posted @ 2011-02-28 17:38  lynn995  阅读(359)  评论(0编辑  收藏  举报