使用php创建和下载文本文件

Jho*_*rra 3 php download createfile

这就是我想要做的.我有一系列报告,他们也希望能够以逗号分隔的文本文件下载.我已经阅读过一堆页面,人们说这些页面只是回显结果而不是创建文件,但是当我尝试它只是输出到它们所在的页面时.

我以每份报告的形式提供此信息

Export File<input type="checkbox" name="export" value="1" />
Run Code Online (Sandbox Code Playgroud)

所以在帖子上我可以检查他们是否正在尝试导出文件.如果他们是我试图这样做:

if($_POST['export'] == '1')
{
    $filename = date("Instructors by DOB - ".$month) . '.txt';

    $content = "";

    # Titlte of the CSV
    $content = "Name,Address,City,State,Zip,DOB\n";

    for($i=0;$i<count($instructors);$i++)
        $content .= ""; //fill content

    fwrite($filename, $content);

    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Length: ". filesize("$filename").";");
    header("Content-Disposition: attachment; filename=$filename");
    header("Content-Type: application/octet-stream; "); 
    header("Content-Transfer-Encoding: binary");

    readfile($filename);
}
Run Code Online (Sandbox Code Playgroud)

基本上页面刷新,但没有文件被推下载.任何人都可以指出我错过了什么?

编辑 我想我并不完全清楚.这不在仅创建和下载文件的页面上,这是在同时显示报告的页面上.所以当我放一个exit(); 在readfile之后,页面的其余部分加载空白.我还需要在此页面上显示报告.我认为这也可能与它为什么不下载有关,因为这个页面已经发送了头信息.

Ult*_*nct 8

在要求您尝试关闭文件之前,我忽略了您写出内容的方式.

在这里查看fwrite手册:http://php.net/manual/en/function.fwrite.php

你需要做的是:

$filename = "yourfile.txt";
#...
$f = fopen($filename, 'w');
fwrite($f, $content);
fclose($f);
Run Code Online (Sandbox Code Playgroud)

关闭文件后,您现在可以安全地将其发送下载.

header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Length: ". filesize("$filename").";");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/octet-stream; "); 
header("Content-Transfer-Encoding: binary");

readfile($filename);
Run Code Online (Sandbox Code Playgroud)

有几件事:

  • 你真的不需要将内容类型设置为application/octet-stream.为什么不设置更真实的类型text/plain
  • 我真的不明白你想如何使用日期功能.请参考这里的手册:http://php.net/manual/en/function.date.php
  • 正如@nickb正确指出的那样,你必须在执行之后退出脚本 readfile(..)