确保在 PHP 代码中没有在 header() 函数调用之前输出了任何内容,包括空格、换行符、HTML 标签等。header() 函数需要在**任何输出** 之前调用。 可以尝试使用 ob_clean() 函数清除输出缓冲区,以确保在输出 CSV 数据之前没有任何其他输出被发送到浏览器。 if ($result->num_rows > 0) { // 清除输出缓冲区 ob_clean(); // 创建文件指针连接到输出流 $output = fopen('php://output', 'w'); // 输出列标题 fputcsv($output, ['col1', 'col2', 'col3']); // 循环输出行数据 while ($row = $result->fetch_assoc()) { fputcsv($output, $row); } // 输出 CSV 文件的头信息 header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=data.csv'); // 关闭文件指针 fclose($output); exit; }