[英]create, write and download a txt file using php
$file = fopen("test.txt", "w") or die("Unable to open file!");
fwrite($file, "lorem ipsum");
fclose($file);
header("Content-Disposition: attachment; filename=\"" . basename($file) . "\"");
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($file));
header("Connection: close");
File is created/open and writen but it is not downloaded. 文件已创建/打开并写入但未下载。
Any help? 有帮助吗?
The correct way to do it would be: 正确的方法是:
<?php
$file = "test.txt";
$txt = fopen($file, "w") or die("Unable to open file!");
fwrite($txt, "lorem ipsum");
fclose($txt);
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
header("Content-Type: text/plain");
readfile($file);
?>
You need to output something in order to let the user download a file. 您需要输出一些内容才能让用户下载文件。 Try this code: 试试这段代码:
$file = fopen("test.txt", "w") or die("Unable to open file!");
fwrite($file, "lorem ipsum");
fclose($file);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="FILENAME"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: test.txt');
ob_clean();
flush();
readfile('text.txt');
exit();
Change FILENAME
with the name of the file you want the user to download. 使用您希望用户下载的文件的名称更改FILENAME
。
After you created a file, you should output it's contents to browser, for example with fpassthru
, as you use file handler: 创建文件后,您应该将其内容输出到浏览器,例如使用fpassthru
,因为您使用文件处理程序:
$path = "test.txt";
$file = fopen($path, "w") or die("Unable to open file!");
fwrite($file, "lorem ipsum");
//fclose($file); // do not close the file
rewind($file); // reset file pointer so as output file from the beginning
// `basename` and `filesize` accept path to file, not file descriptor
header("Content-Disposition: attachment; filename=\"" . basename($path) . "\"");
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($path));
header("Connection: close");
fpassthru($file);
exit();
I think you only need content for the download process 我认为您只需要下载过程的内容
<?PHP
//config
$namefile = "test.txt";
$content = "lorem ipsum";
//save file
$file = fopen($namefile, "w") or die("Unable to open file!");
fwrite($file, $content);
fclose($file);
//header download
header("Content-Disposition: attachment; filename=\"" . $namefile . "\"");
header("Content-Type: application/force-download");
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header("Content-Type: text/plain");
echo $content;
thank you. 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.