Create and download a text file using php

前端 未结 1 1067
无人及你
无人及你 2021-01-14 14:52

Here\'s what I\'m trying to do. I have a series of reports that they also want to be able to download as comma delimited text files. I\'ve read over a bunch of pages where

相关标签:
1条回答
  • 2021-01-14 15: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(..)
    0 讨论(0)
提交回复
热议问题