php在浏览器导出cvs文件
/** * Class ExportCsv * @author http://centphp.com/ */ class ExportCsv { /** * @param $data array 导出数据 * @param $filename string 导出文件名 * @author http://centphp.com/ */ public static function export($data, $filename) { if (!is_array($data)) return; $string = ''; $new = array(); foreach ($data as $k => $v) { foreach ($v as $xk => $xv) { $v[$xk] = str_replace(',', '', $xv); } $new[] = implode(',', $v); } if (!empty($new)) { $string = implode("\n", $new); } header("Content-Type: application/vnd.ms-excel; charset=GBK"); header("Content-Disposition: attachment;filename={$filename}.csv"); echo $string; } /** * 字符编码转码 * @param mixed $content * @param string $from * @param string $to * @return mixed * @author http://centphp.com/ */ public static function charset($content, $from = 'gbk', $to = 'utf-8') { $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from; $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to; if (strtoupper($from) === strtoupper($to) || empty($content)) { //如果编码相同则不转换 return $content; } if (function_exists('mb_convert_encoding')) { if (is_array($content)) { $content = var_export($content, true); $content = mb_convert_encoding($content, $to, $from); eval("\$content = $content;"); return $content; } else { return mb_convert_encoding($content, $to, $from); } } elseif (function_exists('iconv')) { if (is_array($content)) { $content = var_export($content, true); $content = iconv($from, $to, $content); eval("\$content = $content;"); return $content; } else { return iconv($from, $to, $content); } } else { return $content; } } }
使用示例:
$data = [ ['id' => '1', 'name' => '名字1', 'title' => '标题1'], ['id' => '2', 'name' => '名字2', 'title' => '标题2'], ['id' => '3', 'name' => '名字3', 'title' => '标题3'], ['id' => '4', 'name' => '名字4', 'title' => '标题4'], ['id' => '5', 'name' => '名字5', 'title' => '标题5'], ['id' => '6', 'name' => '名字6', 'title' => '标题6'], ['id' => '7', 'name' => '名字7', 'title' => '标题7'], ['id' => '8', 'name' => '名字8', 'title' => '标题8'], ]; ExportCsv::export(ExportCsv::charset($data, 'utf-8', 'gbk'), '测试');