我正在查询我的数据库并使用结果创建 csv 文件。然后我在前端页面上放置了一个指向在服务器上创建的文件的链接,如下所示:
function writetofile($stringData, $myFile) {
$fh = fopen('download/'.$myFile, 'w') or die("can't open file");
fwrite($fh, $stringData);
fclose($fh);
}
$filename = $file."_".date("d-m-Y_H-i",time()).'.csv';
writetofile($seperator, $filename);
print 'Right-click on the link below and select "Save as":' . '<br/><br/>';
print 'Download File: <a href="/download/'.$filename.'" target="_blank">Download Link</a>';
出于某种原因,当我直接从服务器下载文件时,数据库中的所有行看起来都是正确的。但是,当我执行用户将执行的步骤(即右键单击并保存)时,该文件仅包含此页面的 html 代码。
最佳答案
更新看看 http://php.net/manual/en/function.readfile.php
放入合适的php header ,输出文件内容并退出:
<?php // none space here
function writetofile($stringData, $myFile)
{
if ( ! file_exists('download/' . $myFile))
{
echo 'file missing';
}
else
{
header('HTTP/1.1 200 OK');
header('Cache-Control: no-cache, must-revalidate');
header("Pragma: no-cache");
header("Expires: 0");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$myFile");
readfile('download/' . $myFile);
exit;
}
}
无论如何都要调查http://php.net/manual/en/function.fputcsv.php确保正确的 csv 格式...
关于php - 从服务器下载 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14106343/