如何使用php中的“另存为”对话框将特定的CSV文件从服务器下载到客户端


How to download a specific CSV file from the server to the client using Save As dialog box in php?

我在服务器上有一个名为CO2.csv的文件,我希望用户通过表单中的按钮下载并用新文件名将其保存到硬盘驱动器中的任何位置。

这是调用php代码的按钮的Html脚本

 <form action="FCO2.php"  method="post" <?php if(empty($_SESSION["CO2"])){?>style="display:none"<?php } ?> >
    <input type="submit" value="Export to CSV" name="submit">
</form> 

这是FCO2.php

<?php
$file = 'temp/CO2temp.csv';
if(!$file)
{ // file does not exist
    die('file not found');
} 
else 
{
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: text/csv");
    header("Content-Transfer-Encoding: text/csv");
}
?>

但它不起作用,它总是创建一个空文件,并且从不复制位于服务器上的文件。

哦,您只是错过了对实际文件的调用,例如使用readfile

所以添加到:

<?php
$file = 'temp/CO2temp.csv';
if(!$file)
{ // file does not exist
    die('file not found');
} 
else 
{
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: text/csv");
    header("Content-Transfer-Encoding: text/csv");
    readfile($file);
   exit;// good practice but if this is the whole file, its not needed
}
?>

您正在输出一堆头文件,但PHP在输出文件之前就结束了。

您可以使用readfile来完成此操作。