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.
This should work:
header('Content-type: text/plain');
header('Content-disposition: attachment; filename="test.txt"');
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.
To clarify the usage of 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.
So basically, you're changing the entire page when you're using header(). Make sure the only contents you echo are the string.
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?
<?
header ("Content-Type: application/download");
header ("Content-Disposition: attachment; filename=$yourfile");
header("Content-Length: " . filesize("$yourfile"));
$fp = fopen("$yourfile", "r");
fpassthru($fp);
?>