0

我需要一些教育。每个月底,我想从我的网络服务器下载一些数据到我的本地 PC。所以,我为此编写了一个小脚本,它从数据库中选择数据。接下来,我想下载它。我试过这个:

$file=$month . '.txt';
$handle=fopen($file, "w");
header("Content-Type: application/text");
header("Content-Disposition: attachment, filename=" . $month . '.txt');
while ($row=mysql_fetch_array($res))
    {
    $writestring = $row['data_I_want'] . "\r\n";
    fwrite($handle, $writestring);
    }
fclose($handle);

如果我运行它,则创建文件,但我的文件不包含我想要的数据。相反,我从浏览器中的 HTML 文件中得到了转储。我做错了什么。谢谢,Xpoes

4

2 回答 2

3

下面的脚本将帮助您下载创建的文件

//Below is where you create particular month's text file
$file=$month . '.txt';
$handle=fopen($file, "w");
while ($row=mysql_fetch_array($res)){
    $writestring = $row['data_I_want'] . "\r\n";
    fwrite($handle, $writestring);
}
fclose($handle);
//Now the file is ready with data from database

//Add below to download the text file created
$filename = $file; //name of the file
$filepath = $file; //location of the file. I have put $file since your file is create on the same folder where this script is
header("Cache-control: private");
header("Content-type: application/force-download");
header("Content-transfer-encoding: binary\n");
header("Content-disposition: attachment; filename=\"$filename\"");
header("Content-Length: ".filesize($filepath));
readfile($filepath);
exit;
于 2013-06-11T06:12:29.350 回答
0

您当前的代码不输出文件,它只是发送标题。

为了使您的脚本正常工作,请在您的fclose语句后添加以下代码。

 $data = file_get_contents($file);
 echo $data;
于 2013-06-11T06:02:29.077 回答