I’m trying to get a txt file (created on-the-fly) automatically downloaded.
The following code is not working, because the user gets redirected to a page showing the txt instead of downloading it.
What I want, instead, is that clicking on the form (top part of the code) causes the page to refresh (which happens) and then the file downloaded. If a change the file format to rtf, e.g., I can download it, but not a txt.
=================NOT WORKING CODE==================
echo "
<form name=\"fn\" action=\"index.php?option=com_comp\" method=\"post\">
// more not related stuff
<input type=\"image\" src=\"".JURI::root().
"components/com_comp/images/download_icon.png\" .
"\" name=\"downloadaddresses\">DOWNLOAD_RESULTS
// more not related stuff";
if($_POST['downloadaddresses_x']!=0) {
$myfilename = "tmp/results.txt";
$fh = fopen($myfilename, 'w');
$recipients = $_POST['recipients'];
$semicolon_separated = implode(";", $recipients);
fwrite($fh, $semicolon_separated);
fclose($fh);
echo "<a href=\"".$myfilename."\" id=\"downloadlink\">
This download should start automatically!</a>";
echo "<script type=\"text/javascript\">
location.href = document.getElementById('downloadlink').getAttribute('href');
</script>";
}
need to specify the content type in the header of your PHP file