如何使用 PHP 为文本文件显示“另存为”对话框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/732063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to show 'Save as' dialog box using PHP for text files
提问by Click Upvote
How can I show the 'Save as' dialog box using PHP which will ask the user to download a string as a text file? Basically I will retrieve some values from the database, and want then to be able to download a .txt file which contains this data.
如何使用 PHP 显示“另存为”对话框,要求用户将字符串下载为文本文件?基本上我将从数据库中检索一些值,然后希望能够下载包含这些数据的 .txt 文件。
回答by Emil H
This should work:
这应该有效:
header('Content-type: text/plain');
header('Content-disposition: attachment; filename="test.txt"');
回答by Randolpho
Just to expand on @Emil H's answer:
只是为了扩展@Emil H的回答:
Using those header calls will only work in the context of a new request. You'll need to implement something that allows your script to know when it's actually sending the file as opposed to when it's displaying a form telling the user to download the file.
使用这些标头调用仅适用于新请求的上下文。你需要实现一些东西,让你的脚本知道它什么时候真正发送文件,而不是什么时候显示一个表单告诉用户下载文件。
回答by billypostman
<?
header ("Content-Type: application/download");
header ("Content-Disposition: attachment; filename=$yourfile");
header("Content-Length: " . filesize("$yourfile"));
$fp = fopen("$yourfile", "r");
fpassthru($fp);
?>
回答by Frank Crook
To clarify the usage of header():
澄清header()的用法:
header()is used to send a raw HTTP header. See the ? HTTP/1.1 specification for more information on HTTP headers.
Remember that header()must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header()is called. The same problem exists when using a single PHP/HTML file.
header()用于发送原始 HTTP 标头。看到了吗?有关 HTTP 标头的更多信息的 HTTP/1.1 规范。
请记住,header()必须在发送任何实际输出之前调用,无论是通过普通的 HTML 标记、文件中的空行还是来自 PHP。使用include()或require()、函数或其他文件访问函数读取代码,并且在调用header()之前输出空格或空行,这是一个非常常见的错误。使用单个 PHP/HTML 文件时存在同样的问题。
So basically, you're changing the entire page when you're using header(). Make sure the only contents you echo are the string.
所以基本上,当您使用 header() 时,您正在更改整个页面。确保您回显的唯一内容是字符串。

