手搓php 导出csv,由于csv格式简单,故导出速度远远高于phpexcel,不依赖第三方插件 $value) { //这里采用严谨的方式,每个数据列都用双引号包裹,双引号自身用也用双引号转义 $record[$k
$value) { //这里采用严谨的方式,每个数据列都用双引号包裹,双引号自身用也用双引号转义 $record[$key]='"' . str_replace('"', '""', $value) . '"'; } //列与列之间用英文逗号分隔,在每行的最后面加上回车换行 return implode(',', $record)."\r\n"; } //输出第一行数据(通常是列标题); $cols = array('列标题1','列标题2','列标题3', '...'); $retStr .= toCSVRecord($cols); //查询数据库,对每行数据进行如下操作 //位数较多的数字类型的列(如身份证号,订单号等)请手动加单引号【'】 $stmt = $pdo->query('select * from xxx where ....'); while($record=$stmt->fetch()){ $retStr .= toCSVRecord($record); } ob_end_clean(); //最后输出数据并下载(注意:这里是utf8转换成gbk!) $retStr=mb_convert_encoding($retStr, "GBK", "UTF-8"); $now = gmdate("D, d M Y H:i:s"); header("Expires: Thu, 01 Jan 1970 00:00:00 GMT"); header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate"); header("Last-Modified: {$now} GMT"); // force download header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header("Content-Disposition: attachment;filename=data.csv"); Header("Accept-Length: " . strlen($retStr)); header("Content-Transfer-Encoding: binary"); echo $retStr;