views:

2491

answers:

5

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.

+15  A: 

This should work:

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

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.

Randolpho
+1  A: 

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.

Frank Crook
A: 

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

What if my file name have spaces?

I am trying to download files by sending headers, but some files have spaces.

example: test file.txt

SO, what do i do?

Junaid
Filenames with spaces should work fine with that code above, have you tried it?
Click Upvote
A: 
<?
header ("Content-Type: application/download");
header ("Content-Disposition: attachment; filename=$yourfile");
header("Content-Length: " . filesize("$yourfile"));
$fp = fopen("$yourfile", "r");
fpassthru($fp);
?>
billypostman