通过php页面中的js强制下载txt

Force download of a txt via js in php page

本文关键字:下载 txt js php 通过      更新时间:2023-09-26

我正在尝试自动下载一个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>";
        }           

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

header('Content-Type: text/plain'); 
header('Content-Disposition: attachment; filename="your_filename_here.txt"');
echo file_get_contents('path_to_file.txt');

Headers,您得到了这个。

header("Content-type: text/plain")