title: Create and download CSV file in one script
body: <p>I want to create and download a CSV file, in one script.</p>
  
  <p>Up to now I have been avoiding my lack of knowledge by pre-creating the file with a cron job and then 
  downloading the file via a link.</p>
  
  <p>I have this:</p>
  
  <pre><code>$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die ('Error connecting to mysql');
  
  $get_members_csv_query = "SELECT * FROM members";
  $get_members_csv_result=$conn-&gt;query($get_members_csv_query, MYSQLI_STORE_RESULT);
  
  $all_members_array = array();
  
  while ($get_members_csv_array = $get_members_csv_result-&gt;fetch_assoc())
  {
      array_push($all_members_array, $get_members_csv_array);
  }
  
  
  $file = fopen('members.csv', 'w');                              
    fputcsv($file, array('email', 'First Name', 'Surname', 'Gender','DOB','Registered On','Country','paid','Children','Wants Kids','Relationship','Body Type','Height','Smoke','Drink','Phone','Region','Religion','Community'));      
    foreach ($all_members_array as $row) {
          fputcsv($file, $row);              
    }
  
  
        exit(); 
  </code></pre>
  
  <p>This creates the file successfully, but what do I need to add to the script to make it automatically download the CSV file once created?</p>
  
  <p>I have tried putting this at the start if the script:</p>
  
  <pre><code>header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=members.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
  </code></pre>
  
  <p>But it downloads the file before the script finishes (or even starts) creating the file.</p>
  
  <p>I have tries putting the headers at the end of the script and using ob_start() at the top - same result.</p>
  
  <p>Thanks</p>