How to show 'Save as' dialog box using PHP

2020-02-11 02:33发布

问题:

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.

回答1:

This should work:

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


回答2:

Just to expand on @Emil H's answer:

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.



回答3:

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


回答4:

To clarify the usage of header():

Official PHP Manual:

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.

So basically, you're changing the entire page when you're using header(). Make sure the only contents you echo are the string.