导出CSV文件使用PHP创建损坏的文件时,试图打开MS Excel


Export CSV file using PHP create corrupt file when try to open in MS Excel

我有以下脚本,将导出数据从我的数据库使用php到csv文件。一切都很好,除了当我试图在excel中打开文件时,我得到"文件损坏"。当我运行这段代码时,它显示了错误-"文件已损坏,无法打开。"提前感谢!

<?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;
?>

我找到了自己问题的答案。只需要在调用头文件下载csv文件之前添加ob_clean()行来清除输出缓冲区。这将解决在excel中无法打开csv文件的错误。