title: Export CSV file using PHP create corrupt file when try to open in MS Excel
body: <p>I have the following script that will export data from my database using php to csv file. Everything works fine, except when I try to open the file in excel, I get "file is corrupt". When I run this code it shows the error - "The file is corrupted and can not be opened." Thanks in advance!</p>
  
  <pre><code>&lt;?php
  
  // Connection
  include_once('conn.php');
  
  $sql = "select * from info";
  $qur = mysql_query($sql);
  
  // Enable to download this file
  $filename = "sampledata.csv";
  
  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: text/csv");
  
  $display = fopen("php://output", 'w');
  
  $flag = false;
  while($row = mysql_fetch_assoc($qur)) {
      if(!$flag) {
        // display field/column names as first row
        fputcsv($display, array_keys($row), ",", '"');
        $flag = true;
      }
      fputcsv($display, array_values($row), ",", '"');
    }
  
  fclose($display);
  exit;
  ?&gt;
  </code></pre>