title: Create and download a text file using php
body: <p>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 people say simply echo out the results rather than creating a file, but when I try that it just outputs to the page they are on.  </p>
  
  <p>I have this in the form of each report</p>
  
  <pre><code>Export File&lt;input type="checkbox" name="export" value="1" /&gt;
  </code></pre>
  
  <p>So on the post I can check if they are trying to export the file. If they are I was trying to do this:</p>
  
  <pre><code>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&lt;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);
  }
  </code></pre>
  
  <p>Basically the page refreshes, but no file is pushed for download.  Can anyone point out what I'm missing?</p>
  
  <p><strong>EDIT</strong>
  I think I wasn't entirely clear.  This is not on a page that only creates and downloads the file, this is on a page that is also displaying the report.  So when I put an exit(); after the readfile the rest of the page loads blank.  I need to display the report on this page as well.  I think this could also have to do with why it's not download, because this page has already sent header information.</p>