php 导出csv
public function doworks(){
//输出Excel文件头,可把user.csv换成你要的文件名
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="user.csv"');
header('Cache-Control: max-age=0');
header("Content-type: text/html; charset=utf-8");
// 打开PHP文件句柄,php://output 表示直接输出到浏览器
$fp = fopen('php://output', 'a');
//输出Excel列名信息
$head = array('商品名字', '商品_id', '商品—version', '商品—ad');
$mm = M('home_product_on');
$stmt= $mm->query("select product_name,product_id,version_id,product_ad from __TABLE__ limit 100" );
// CSV的Excel支持GBK编码,一定要转换,否则乱码
foreach($head as $i=> $v){
// $head[$i] = iconv('utf-8','gbk',$v);
}
$i=0;
foreach($stmt as $val){
$stmt[$i]['version_id'] ='\''.$val['version_id'].'\'';
$i++;
}
$cnt=0;// 计数器
$limit=100000;// 每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
fputcsv($fp, $head);//将数据通过fputcsv写到文件句柄
//逐行取出数据,不浪费内存
// while($row = $stmt->fetch(Zend_Db::FETCH_NUM)){
foreach($stmt as $row){
$cnt ++;
if($limit == $cnt){//刷新一下输出buffer,防止由于数据过多造成问题
ob_flush();
flush();
$cnt = 0;
}
foreach($row as $i => $v){
// $row[$i] = iconv('utf-8', 'gbk', $v);
}
fputcsv($fp, $row);
}
}