我需要一些教育。 在每个月末,我想从我的网络服务器下载一些数据到我的本地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
答案 0 :(得分: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;
答案 1 :(得分:0)
您当前的代码不输出文件,它只是发送标题。
为了让您的脚本正常工作,请在fclose
语句后添加以下代码。
$data = file_get_contents($file);
echo $data;