折腾了几次 搜索了好久 终于找到办法
/** * http://yige.org/php/ * @ string 需要转换的文字 * @ encoding 目标编码 **/ function convert_encoding($string, $encoding = 'gbk'){ $is_utf8 = preg_match('%^(?:[x09x0Ax0Dx20-x7E]| [xC2-xDF][x80-xBF]| xE0[xA0-xBF][x80-xBF] | [xE1-xECxEExEF][x80-xBF]{2} | xED[x80-x9F][x80-xBF] | xF0[x90-xBF][x80-xBF]{2} | [xF1-xF3][x80-xBF]{3} | xF4[x80-x8F][x80-xBF]{2} )*$%xs', $string); if($is_utf8 && $encoding == 'utf8'){ return $string; }elseif($is_utf8){ return mb_convert_encoding($string, $encoding, "UTF-8"); }else{ return mb_convert_encoding($string, $encoding, 'gbk,gb2312,big5'); } }
应用办法
/** * 输出一个csv头,用于下载 * @param string $filename, 输出的下载文件名 * @return null */ function csv_header_4_downloading($filename, $encode = 'UTF-8') { header('Content-Encoding: ' . $encode); header('Content-type: text/csv; charset=' . $encode); header("Content-Disposition: attachment; filename={$filename}.csv"); if (strtolower($encode) == 'utf-8') echo "xEFxBBxBF"; // UTF-8 BOM } /** * 导出数据为excel表格 *@param $data 一个二维数组,结构如同从数据库查出来的数组 *@param $title excel的第一行标题,一个数组,如果为空则没有标题 *@param $filename 下载的文件名 *@examlpe $stu = M ('User'); $arr = $stu -> select(); exportexcel($arr,array('id','账户','密码','昵称'),'文件名!'); */ function export2excel($data=array(), $title=array(), $filename='report'){ ob_clean(); csv_header_4_downloading($filename, 'gbk'); //导出xls 开始 if (!empty($title)){ foreach ($title as $k => &$v) { $v = convert_encoding($v, 'gbk'); } $title= implode("","", $title); echo ""$title" "; } if (!empty($data)){ foreach($data as $key => &$val){ foreach ($val as $ck => &$cv) { $cv = str_replace(',', ',', $cv); $cv = str_replace(""", "\"", $cv); $cv = str_replace(" ", "", $cv); $cv = str_replace(" ", "", $cv); $cv = strip_tags($cv); $cv = convert_encoding($cv, 'gbk'); } $val = implode("","", $val); echo ""$val" "; } } exit(); }