我正在做的是查询数据库以构建CSV文件。我正在使用这些标题来保存文件:
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="export.csv"');
它在我的WAMP设置上本地工作,但在服务器上不工作。PHP或Apache中是否有需要更改的设置或其他内容?
当我在本地点击链接时,它会下载一个CSV文件。当我在实时服务器上做同样的事情时,它只会把我带到生成CSV内容的php页面。
尝试使用application/octet-stream
而不是text/csv
。我不知道为什么你的浏览器在不同的域中表现不同,但使用application/octet-stream
更常见。RFC2616中提到了这一点。由于您没有在浏览器中显示它,因此内容类型不必与内容匹配。
我遇到了和你一样的问题。在我的情况下,解决方案是我们只需要使用include 'connection_file.php';
之后
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
意味着您的头文件必须是该文件的第一条语句。
导出csv的完整PHP代码是:
<?php
if(isset($_POST['Export'])){
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
include '../dbcon.php';
$output = fopen("php://output", "w");
fputcsv($output, array('id', 'name', 'phone', 'Employee Name', 'district', 'taluka', 'address'));
$query = "SELECT * from export_buffer ORDER BY id DESC";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($output, $row);
}
fclose($output);
}
?>