直接上代码
public function doExcel($data)
{
// 文件名
$filename = date('YmdHis') . '.csv';
// 文件完整路径
$filepath = dirname(dirname(__FILE__)) . '/' . $filename;
// 打开文件,没有自动创建
$fp = fopen($filepath, 'a');
// 设置导航栏
$headers = array('手机号','地市');
$content = implode(',', $headers) . PHP_EOL;
// 填充数据
foreach ($data as $value) {
$content .= $value['phone'] . ',' . $value['name'] . PHP_EOL;
}
// 写入数据
fwrite($fp, $content);
// 关闭文件
fclose($fp);
// 设置header
header("Pragma: public");
header("Expires: 0");
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
header("Content-Type:application/force-download");
header("Content-Type:application/vnd.ms-execl");
header("Content-Type:application/octet-stream");
header("Content-Type:application/download");;
header('Content-Disposition:attachment;filename='.$filename);
header("Content-Transfer-Encoding:binary");
// 输出到浏览器
readfile($filepath);
// 删除本地文件
unlink($filepath);
}
本文介绍了一种使用PHP进行CSV文件导出的方法,并详细展示了如何将数组数据转换为CSV格式,随后通过浏览器下载该文件。同时,文章还提供了完整的代码示例,包括设置HTTP头部信息来触发文件下载。
370

被折叠的 条评论
为什么被折叠?



