Create and download a text file using php

我的未来我决定 提交于 2019-12-01 09:26:11

I overlooked the way you are writing out the contents before asking you to try closing the file.

Check the fwrite manual here: http://php.net/manual/en/function.fwrite.php

What you need to do is:

$filename = "yourfile.txt";
#...
$f = fopen($filename, 'w');
fwrite($f, $content);
fclose($f);

and after closing the file, you can now safely send it across for download.

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);

There are a couple of things:

  • You really dont need to set the content-type as application/octet-stream. Why not set a more real type as text/plain?
  • I really dont understand how you want to use the date functionality. please refer to the manual here: http://php.net/manual/en/function.date.php
  • As correctly pointed out by @nickb, you must exit the script after doing the readfile(..)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!