Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何显示';另存为';使用PHP处理文本文件的对话框_Php_Http_Mime Types - Fatal编程技术网

如何显示';另存为';使用PHP处理文本文件的对话框

如何显示';另存为';使用PHP处理文本文件的对话框,php,http,mime-types,Php,Http,Mime Types,如何使用PHP显示“另存为”对话框,该对话框将要求用户下载字符串作为文本文件?基本上,我将从数据库中检索一些值,然后希望能够下载包含这些数据的.txt文件。这应该可以: header('Content-type: text/plain'); header('Content-disposition: attachment; filename="test.txt"'); 只想进一步说明@Emil H的答案: 使用这些头调用只能在新请求的上下文中工作。您需要实现一些功能,使脚本能够知道何时实际发送文

如何使用PHP显示“另存为”对话框,该对话框将要求用户下载字符串作为文本文件?基本上,我将从数据库中检索一些值,然后希望能够下载包含这些数据的.txt文件。

这应该可以:

header('Content-type: text/plain');
header('Content-disposition: attachment; filename="test.txt"');

只想进一步说明@Emil H的答案:

使用这些头调用只能在新请求的上下文中工作。您需要实现一些功能,使脚本能够知道何时实际发送文件,而不是何时显示通知用户下载文件的表单。

要澄清header()的用法:

:

header()用于发送原始HTTP头。有关HTTP头的更多信息,请参阅»HTTP/1.1规范

记住,在发送任何实际输出之前,必须调用header(),可以是通过普通HTML标记、文件中的空行,也可以是通过PHP。使用include()或require()函数或其他文件访问函数读取代码,并在调用header()之前输出空格或空行,这是一个非常常见的错误。使用单个PHP/HTML文件时也存在同样的问题

因此,基本上,当您使用header()时,您正在更改整个页面。确保只回显字符串。


<?
header ("Content-Type: application/download");
header ("Content-Disposition: attachment; filename=$yourfile");
header("Content-Length: " . filesize("$yourfile"));
$fp = fopen("$yourfile", "r");
fpassthru($fp);
?>

把这个放在这里,因为除了埃米尔的答案,我还需要它。。。。换行符:回显“\r\n”;