PHP导出到excel不显示UTF-8

标签 php mysql utf-8

我正在尝试通过 SQL 查询将数据导出到 Excel。它可以工作,但不显示语言。

我正在使用 SET CHARACTER SET UTF-8,但它不起作用。

这是我的代码:

$sql = "Select * from $DB_TBLName";

$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database   
$Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());   

mysql_query("SET CHARACTER SET UTF-8",$Connect); 

$result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());    

$file_ending = "xls";

//header info for browser
header('Content-Encoding: TIS620');
header('Content-type: text/csv; charset=UTF-8');
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename.xls");  
header("Expires: 0");
/*******Start of Formatting for Excel*******/   
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");    
//end of printing column names  
//start while loop to get data
    while($row = mysql_fetch_row($result))
    {
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }

        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        $schema_insert = iconv(mb_detect_encoding($schema_insert, mb_detect_order(), true), "UTF-8", $schema_insert);
        print(trim($schema_insert));
        print "\n";
    }   

当该字段使用我的区域语言时,该字段具有外来语言。

最佳答案

不要使用mysql_*接口(interface);切换到 mysqli_*PDO

不要使用iconv()

务必包含设置名称 utf8

关于PHP导出到excel不显示UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35789800/

相关文章:

php - mysql选择范围内的最后x天

php - session 可以在本地主机上运行,​​但不能在服务器上运行(Ipage 等..)

java - MySQL 数据库在 8 小时后断开连接。如何预防?

grails - 从GSP到Controller编码非UK字符的Grails

utf-8 - 如何确定文件编码?

php - UTF-8贯穿始终

php - LswMemcacheBundle 中的缓存生命周期

php - 将 PHP 模板文件编译成静态 HTML 页面的 Ant 任务

MySQL LIMIT 只有父 JOIN

php - 打开两个唯一的 mysql 连接?