小泽php成长经历的博客

记录工作和学习中自己遇到解决的经验

php导出csv文件

//导出csv格式的表格
public function exportcsv() {
$keyword=trim(I('keyword'));
$where['nickname|openid'] = array('like','%'.$keyword.'%');
$data= M('user')->where($where)->select();
$str = "序号,姓名,关注,openid,昵称,性别,城市,国家,省份,语言,头像,关注时间,unionid,备注,创建时间,用户组\r\n";
foreach($data as $key=>$value){
$id = $value['id'];
$name = $value['name'];
$subscribe = $value['subscribe'];
$openid = $value['openid'];
$nickname = $value['nickname'];
$sex = $value['sex'];
$city = $value['city'];
$country = $value['country'];
$province = $value['province'];
$language = $value['language'];
$headimgurl = $value['headimgurl'];
$subscribe_time = $value['subscribe_time'];
$unionid = $value['unionid'];
$remark = $value['remark'];
$ctime = date('Y-m-d H:i:s',$value['ctime']);
$groupid = $value['groupid'];
$str .= "".$id.",".$name.",".$subscribe.",".$openid.",".$nickname.",".$sex.",".$city.",".$country.",".$province.",".$language.",".$headimgurl.",".$subscribe_time.",".$unionid.",".$remark.",".$ctime.",".$groupid."\r\n";
//$str .="".$name.",".$section1.",".$phone.",".$section_name.",".$ordertime.",".$content.",".$addtime.",".$idcard."\r\n";
}
$filename = date('Ymd').'.csv'; //设置文件名
if(filesize($file)>1024){
$file = getcwd().'/aaa.csv';
//dump($file);exit;
file_put_contents($file,$str);
//dump($str);exit;
if (file_exists($file)) {
$filesize=filesize($file)+1000;

header('Content-Description:File Transfer');
header('Content-type:'.csv);
header('Content-Transfer-Encoding:binary');
header("Accept-Ranges: bytes");
header('Expires:0');
header('Cache-Control:must-revalidate');
header('Pragma:public');
header("Content-Length:".$filesize);
header('Content-Disposition: attachment; filename='.$filename);
//打开文件
$fp = fopen($file, "rb");
//dump($fp);exit;
//设置指针位置
fseek($fp,0);
while (!feof($fp)) {
//虚幻输出
//设置文件最长执行时间
set_time_limit(0);
print (fread($fp, 1024 * 150)); //输出文件
flush(); //输出缓冲
ob_flush();
}
fclose($fp);

unlink($file);
exit ();
}else{
echo "err";die();
}
}else{
header("Content-type:text/csv");
header("Content-Disposition:attachment;filename=".$filename);
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
echo $str;
}
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34770233/article/details/52372708
文章标签: php csv
上一篇获取html的当前级以及上一级的导航名称
下一篇导出csv文件时,处理分隔符问题
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭