【发布时间】:2019-07-13 05:36:06
【问题描述】:
我正在尝试使用 PHP 将 MS SQL 查询返回的数据输出到 Excel 或 CSV 文件。 我在this answer中使用了脚本,可以输出文件OK了。如果没有标题行(在我的代码底部),它会保存在我的服务器的文件夹结构中,而不是作为下载输出到浏览器。
如果我添加标题行,它会输出到 CSV 文件,但会将页面的 HTML 写入文件而不是从数据库中提取!我在某处缺少设置吗?我尝试在没有 HTML 的页面上运行代码(仅限 PHP 和 SQL 代码),但它仍然会发生。
// Give the file a suitable name:
$FileName= $PartNumber.".csv";
$fp = fopen($FileName, 'w');
// Connect to MS SQL server; the actual database is chosen in the form
// ConnSQL defined in inc/dbconn/config.php
ConnSQL($idDatabase);
// the query is a biggie; here it is:
require 'inc_sql.php';
// run it through the SQL server
$rstBOM = sqlsrv_query($GLOBALS['ConnSQL'], $sqlBOM);
while ($export= sqlsrv_fetch_array($rstBOM, SQLSRV_FETCH_ASSOC)) {
if (!isset($headings))
{
$headings = array_keys($export);
fputcsv($fp, $headings, ',', '"');
}
fputcsv($fp, $export, ',', '"');
}
// force download csv - exports HTML to CSV!
header("Content-type: application/force-download");
header('Content-Disposition: inline; filename="'.$FileName.'"');
header("Content-Transfer-Encoding: Binary");
header("Content-length: ". filesize($FileName));
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="'.$FileName.'"');
fclose($fp);
请问我哪里出错了?
【问题讨论】:
标签: php sql-server csv download