【发布时间】:2011-06-04 04:32:09
【问题描述】:
我在导出使用 php 从我的一个 mysql 表创建的 csv 文件时遇到了一些问题。
我使用的代码打印了正确的数据,但我看不到如何在 csv 文件中下载这些数据,并提供了指向所创建文件的下载链接。我认为浏览器应该自动提供文件以供下载,但事实并非如此。 (会不会是因为下面的代码是用ajax调用的?)
非常感谢任何帮助 - 下面的代码,S.
include('../cofig/config.php'); //db connection settings
$query = "SELECT * FROM isregistered";
$export = mysql_query($query) or die("Sql error : " . mysql_error());
$fields = mysql_num_fields($export);
for ($i = 0; $i < $fields; $i++) {
$header .= mysql_field_name($export, $i) . "\t";
}
while ($row = mysql_fetch_row($export)) {
$line = '';
foreach ($row as $value) {
if ((!isset($value) ) || ( $value == "" )) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line) . "\n";
}
$data = str_replace("\r", "", $data);
if ($data == "") {
$data = "\n(0) Records Found!\n";
}
//header("Content-type: application/octet-stream"); //have tried all of these at sometime
//header("Content-type: text/x-csv");
header("Content-type: text/csv");
//header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=export.csv");
//header("Content-Disposition: attachment; filename=export.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo '<a href="">Download Exported Data</a>'; //want my link to go in here...
print "$header\n$data";
【问题讨论】: