-1

我正在尝试自动下载一个 txt 文件(即时创建)。以下代码不起作用,因为用户被重定向到显示 txt 而不是下载它的页面。相反,我想要的是单击表单(代码的顶部)导致页面刷新(发生)然后下载文件。如果将文件格式更改为 rtf,例如,我可以下载它,但不能下载 txt。

=================不工作代码==================

      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>";
        }           
4

2 回答 2

4

需要在 PHP 文件的头部指定内容类型

header('Content-Type: text/plain'); 
header('Content-Disposition: attachment; filename="your_filename_here.txt"');
echo file_get_contents('path_to_file.txt');
于 2012-09-13T20:04:45.737 回答
0

标题,你明白了。

header("Content-type: text/plain")
于 2012-09-13T19:59:56.430 回答