php导出mysql到excel乱码怎么办

php导出mysql到excel乱码的解决办法:首先设置时区以及head头信息;然后通过“ob_end_clean();”清除缓冲区;接着设置表格信息;最后查询内容导出数据库数据即可。

推荐:《PHP视频教程》

PHP查询数据库导出excel并且解决乱码问题,原生代码无需插件

近日写一个信息系统,需要把数据库的内容导出到excel

下面把我的贴出我的代码,不需要phpexcel插件

系统要求:php5.6+

<?php
date_default_timezone_set('PRC');//设置时区
 
/*设置head头信息*/
ob_end_clean();//清除缓冲区,避免乱码
Header("Content-Type:application/vnd.ms-excel;charset=UTF-8");
Header("Accept-Ranges:bytes");
Header("Content-Disposition:attachment;filename="."导出excel的名字".date('YmdHis').".xls");
Header("Pragma:no-cache");
Header("Expires:0");
 
$str = $str2 = null;
/*设置表格信息*/
$str.= "序号"."	";
$str.= "学号"."	";
$str.= "姓名"."	";
$str.= "性别"."	";
$str.= "学院"."	";
$str.= "年级"."	";
$str.= "班级"."	";
$str.= "手机号"."	";
$str.= "报名时间"."	
";
$info = iconv("UTF-8","GBK",$str);
echo $info;
 
/*查询内容导出数据库数据*/
$con = new mysqli("localhost", "root", "password", "detabase");
if (!$con) {
    die(mysqli_error()) ;
}
//$sql = " select * from bmxx";
//$res = mysqli_query($con, $sql);
 
mysqli_query($con,"SET NAMES utf8");//解决数据库中有汉字时显示在前台出现乱码问题
$result = mysqli_query($con,"SELECT * FROM `bmxx`");
 
while($row = mysqli_fetch_assoc($result)){
    $list[] = $row;
}
mysqli_free_result($result);
mysqli_close($con);
$co = 1;
foreach($list as $v){
    $str2.= trim($co++)."	";
    $str2.= trim(iconv("UTF-8","GBK","	".$v['num']."	"))."	";
    $str2.= trim(iconv("UTF-8","GBK",$v['name']))."	";
    $str2.= trim(iconv("UTF-8","GBK",$v['sex']))."	";
    $str2.= trim(iconv("UTF-8","GBK",$v['xueyuan']))."	";
    $str2.= trim(iconv("UTF-8","GBK",$v['grade']))."	";
    $str2.= trim(iconv("UTF-8","GBK",$v['class']))."	";
    $str2.= trim(iconv("UTF-8","GBK",$v['phone']))."	";
    $str2.= trim(iconv("UTF-8","GBK",$v['time']))."	
";
}
echo $str2;
?>

一开始没有加这行代码,导致输出乱码。在每次生成数据之前,清除一下缓冲区就好了、

ob_end_clean();//清除缓冲区,避免乱码

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » php导出mysql到excel乱码怎么办