Php文本框输出是打印而不是下载

时间:2017-05-18 11:51:21

标签: php download

这个问题与其他问题不同。那个问题是关于IF的情况。但是这个问题,而不是下载文件,它是在下一页打印。请不要将此问题与其他人混淆。

我写了一个下载文本框输出的脚本。此脚本在本地服务器上运行正常,它成功下载文件但是当我将脚本放在实时服务器上时,下载文件不起作用。单击download output按钮时,页面输出将显示在下一页上,而不是下载文件。

在此处查看实时脚本:http://www.globalitsoft.net/scripts/test.php

以下是脚本代码:

<?php

    error_reporting(0);
    $mytext = "";

    $txt = preg_replace('/\n+/', "\n", trim($_POST['inputtext']));
    $text = explode("\n", $txt);
    $output  = array();        

    if(isset($_POST["submit"]) || isset($_POST["download"]) ) {        
        for($i=0;$i<count($text);$i++) {    
            $output[] .= trim($text[$i]) . ' AAAAA'.PHP_EOL;    
        }    
    }

    if(isset($_POST["download"]) ) {
      ob_clean();   
      $filename = "file-name-" .date('mdY-His'). '.txt';                    
      $handle = fopen('php://output', "w");
      fwrite($handle, implode($output));
      fclose($handle);
      header('Content-Description: File Transfer');
      header("Content-type: application/force-download");
      header("Content-Type: application/octet-stream charset=utf-8");
      header('Content-Disposition: attachment; filename="'.basename($filename).'"');
      header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
      header('Expires: 0');
      header('Pragma: public');
      header('Content-Transfer-Encoding: binary');
      header('Content-Length: ' . strlen(implode($output)));
      readfile($filename);

      exit();        
    }     
?>


<form method="POST" action="test.php">
    <textarea name="inputtext" rows="10" cols="100" placeholder="Enter Any Text!" required><?php if(!empty($_POST["inputtext"])) { echo $_POST["inputtext"]; } ?></textarea>
    <br><br>
    <input type="submit"  name="submit" value="Do it!">
    <br><br>
    <p>Output goes here. </p>
    <textarea name="oputputtext" rows="10" cols="100" ><?php echo implode($output);?></textarea>
    <input type="submit"   name="download" value="Download Output">
</form>

1 个答案:

答案 0 :(得分:0)

这对我有用:

$handle = fopen("file.txt", "w");
fwrite($handle, "text1.....");
fclose($handle);

header('Content-Type: application/octet-stream');
//You dont need to enclose the filename value in quotes
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;