【发布时间】:2014-01-17 09:10:05
【问题描述】:
我想我遗漏了一些明显的东西。我正在尝试将数据集从 MySQL 查询导出到 CSV,而不将其打印到浏览器。
这是我的代码:
<?php
$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
$data = file_get_contents('php://output'); // Read the file's contents
$name = 'data.csv';
force_download($name, $data);
fclose($fp);
?>
$stories 是我从 MySQL 查询创建的数组。
目前所有内容都打印到浏览器,没有错误,也没有下载,但我想强制下载 CSV。我该怎么做?
最终工作代码:
$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
$data = file_get_contents('php://output');
$name = 'data.csv';
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Disposition: attachment; filename="'.basename($name).'"'); // Add the file name
header('Content-Transfer-Encoding: binary');
header('Connection: close');
exit();
force_download($name, $data);
fclose($fp);
【问题讨论】:
-
你需要输出一个Header来强制下载(我认为这是最好的方式)
-
谢谢,我确实尝试过,但下载的 csv 包含我的 html 而不是数据库中的数据。我正在使用这个附加代码
header('Content-type: application/csv'); header('Content-Disposition: attachment; filename="data.csv"'); -
您是否制作了正确的 csv 文件?当您在浏览器中打开它时,它允许您将其保存到您的桌面?
-
是的,将文件保存到桌面,但我下载的 csv 文件充满了 html 而不是数据库查询
-
你是如何创建文件的?
标签: php mysql codeigniter csv