title: PHP Force download includes HTML source code
body: <p>I have a form which runs a query against a mySQL database upon hitting the submit button. I want to capture that result result and force the user to download a file. I got everything working but the file being downloaded includes the source code of my HTML page. Note that the code below is within my main index file so it has other code above it such as the doctype, header, body tags.</p>
  
  <pre><code>    &lt;?php
      # Convert result to csv and push use to download if user pressed "Download" button
      if(isset($_POST["downloadquery"])) {
          $fp = fopen('php://output', 'w');
          ob_start();
          if ($fp &amp;&amp; $result) {
              fputcsv($fp, $headers); # populate header
              while ($row = $result-&gt;fetch_array(MYSQLI_NUM)) {
                  fputcsv($fp, array_values($row)); #populate rows
              }
          }
          $content = ob_get_clean();
          $filename ='queryResults' . date('Ymd');
  
          // Output CSV-specific headers
          header('Pragma: public');
          header('Expires: 0');
          header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
          header('Cache-Control: private', false);
          header('Content-Type: application/octet-stream');
          header('Content-Disposition: attachment; filename="' . $filename . '.txt";');
  
          exit($content);
      }
      ?&gt;
  </code></pre>