所以我试图通过 php 将 mysql 表导出到 csv 文件。这是代码
<?php if (isset($_POST['exp'])) {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('User ID', 'User Name', 'Password'));
$con = mysqli_connect('localhost', 'root', 'pass', 'xyz');
$rows = mysqli_query($con, 'SELECT * FROM users');
while ($row = mysqli_fetch_assoc($rows)) {
fputcsv($output, $row);
}
fclose($output);
mysqli_close($con);
}
?>
<div>
<form action="#" method="post">
<input type="submit" value="Export" name="exp" />
</form>
</div>
一切都很好,但 html 部分也被转储到 csv 文件中。这是 csv 的屏幕截图
为什么会这样?我做错了什么吗?
最佳答案
您的页面在 PHP 之外继续加载。在 IF 语句的末尾添加 exit()
,它将立即停止运行。
<?php if (isset($_POST['exp'])) {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('User ID', 'User Name', 'Password'));
$con = mysqli_connect('localhost', 'root', 'pass', 'xyz');
$rows = mysqli_query($con, 'SELECT * FROM users');
while ($row = mysqli_fetch_assoc($rows)) {
fputcsv($output, $row);
}
fclose($output);
mysqli_close($con);
exit();
}
?>
<div>
<form action="#" method="post">
<input type="submit" value="Export" name="exp" />
</form>
</div>
关于php - 通过 php..html 将 mysql 表数据导出到 csv 文件也被转储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26593578/