使用php创建,编写和下载txt文件

时间:2018-09-19 16:37:40

标签: 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");

已创建/打开并写入文件,但未下载文件。

有帮助吗?

4 个答案:

答案 0 :(得分:3)

正确的方法是:

<?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);

?>

答案 1 :(得分:0)

您需要输出一些内容,以便用户下载文件。 尝试以下代码:

$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();

用您要用户下载的文件名更改FILENAME

答案 2 :(得分:0)

创建文件后,应在使用文件处理程序时将其内容输出到浏览器,例如,用fpassthru输出:

ID      Col        Persistence
1       0769       1
1       0772       1  
1       0779       1
1       0782       1
1       0799       2
1       0802       2
1       0812       3
2       0769       1
2       0772       1
2       0779       1
3       0782       1
3       0799       2
3       0802       2
3       0812       3

答案 3 :(得分:0)

我认为您只需要下载内容

<?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;

谢谢。