首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用php创建、编写和下载txt文件

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

Stack Overflow用户
提问于 2018-09-19 16:37:40
回答 4查看 28.1K关注 0票数 3
代码语言:javascript
复制
$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");

文件是创建/打开和写的,但没有下载。

有什么帮助吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-09-19 16:48:47

正确的做法是:

代码语言:javascript
复制
<?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);

?>
票数 13
EN

Stack Overflow用户

发布于 2018-09-19 16:48:33

为了让用户下载一个文件,您需要输出一些内容。试试下面的代码:

代码语言:javascript
复制
$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

票数 0
EN

Stack Overflow用户

发布于 2018-09-19 16:49:00

在创建文件之后,应该将输出it的内容到浏览器,例如使用fpassthru,因为您使用了文件处理程序:

代码语言:javascript
复制
$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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52410546

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档