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.= "序号"."\\t"; $str.= "学号"."\\t"; $str.= "姓名"."\\t"; $str.= "性别"."\\t"; $str.= "学院"."\\t"; $str.= "年级"."\\t"; $str.= "班级"."\\t"; $str.= "手机号"."\\t"; $str.= "报名时间"."\\t\\r\\n"; $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++)."\\t"; $str2.= trim(iconv("UTF-8","GBK","\\t".$v['num']."\\t"))."\\t"; $str2.= trim(iconv("UTF-8","GBK",$v['name']))."\\t"; $str2.= trim(iconv("UTF-8","GBK",$v['sex']))."\\t"; $str2.= trim(iconv("UTF-8","GBK",$v['xueyuan']))."\\t"; $str2.= trim(iconv("UTF-8","GBK",$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']))."\\t\\r\\n"; } echo $str2; ?>
一开始没有加这行代码,导致输出乱码。在每次生成数据之前,清除一下缓冲区就好了、
ob_end_clean();//清除缓冲区,避免乱码