php导出mysql到excel乱码怎么办

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

php导出mysql到excel乱码怎么办

推荐:《PHP视频教程

P[ s u _ m A P +HP查询数据库导出excel并且解决乱码Q [ - + _问题,原生代码无需插件

近日写一个信E p ^ q 5 - x系统,需要h ! L 8 H @ J L把数据库的内容导出到excel

下面把我的贴出我的代码,不需要phpexc- r I M S s del插件+ e I N x M

系统要求:php5.6+

<?php
date_default_timezone_set('Pt ? S ! uRC');//设置时区
/*设置head头信息*/
ob_end_clean();//清除缓冲区,避免乱码
Header("Content-Type:application/vnd.ms-excel;charset=UTF-8");
Header("Al e &ccept-Ra! C [ H # nges:bytes");
Header("Content-DispositioX A H _n:attachment;filename="."导出h A L Mexcel的名字".date('YmdHis').".xls")4 _ 2;
Header("Pragma:no-cacP 0 c Z b S zhe");
Header("Expires:0");
$str = $str2 = null;
/*设置表w | ) : _ X格信息*/
$str.= "序号"."\^  y u q x `t";
$str.= "学号"."\t";
$sd a c rtr.= "姓名"."\t";
$str.= "性别") y V r C i { k $."\t";
$str.= "学院"."\t";
$stS b +r.= "年级"."\t";
$str.= "班级".6 K )"\t";
$str.= a _ V  t 0 v"手机号"."\t";
$str.= "报名时间"n { h."\t\r\n"j D ` i &;
$info = iconv("UTF-8","GBK",$str)@ T C [;
echo $info;
/*查询内容导出数据库数据*/
$cox * T 7 5 0 !n = new mysqli("localhost", "root", "password", "detabase");
if (!$con) {
die(mysqli_error()) ;
}
//$sql = " select * from bmxx";
//$reU 9 . X p ws = mysqli_query($con, $sql);
my= ) Y m i Gsqli_query($con,"SET NAMES@ ( X  j utf8");//解决数据库中有汉字时显示在前台出现乱码问题
$result = mysqli_query($con,"SELECT * FROM `bmxx`| - } y ) T l");
whC  i wile($row = mysqli_fetch_assoc($result)){
$list[] = $row;
}
mysqli_free_result($resuln z w ! L I t);
mysqli_close($con);
$co = 1;
foreach($list as $v){
$str2.= trim($co++)."\t";
$str2.= trim(iconv("UTF-8","GBK","\t".$v['num']."W e T k l + g e @t"))."\t";
$str2.= trim(iconv("UD d u / ^ K . h }TF-8","GBK",$v['name']))."\t";
$str2Q U v c V.= trim(iconv("UTF-8","GBK",$v[_ F 3 Q 2'M 7 $ T / e T X fsex']))."\t";
$str2.= t( p 8 ~ s ] p 8 Zrim(iconv("UTF-8","GBK",$v['xueyuan'])).") * Z\t";
$str2.= trim(iconv("UTF-8l S I c H _ 4 V y","GBT | & V G M {K",$v['grade']))."\t";
$str2.= trim(iconv("UTF-8","GBK",$v['class']))."\t";
$str2.= trim(iconv("UTF-8","GBK",$v['phone']))."\t";
$str2.= trim(iconv("UTF-8","GBK",$v['time'[ & o 1 6 & V , f]))."\t\r\n";
}
echo $str2;
?>

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

ob_end_clean();Q F ! q v F a # a//清除缓冲区,避免乱码

以上就是php导出mysql到excel乱码怎么办的详细内容。