我有一个文本输入区域和一个HTML表单中的提交按钮。文本区域的输入是一个SQL查询,该查询命中我的数据库并在前端显示结果。
现在,我有一个新要求,即它也应该将结果存储在文件中并下载。因此,我试图将结果写入临时文件并下载。这是我的代码片段,用于显示和下载临时文件,如here所示。
<html>
<form method="POST">
<input type="text" name="urlid"><br>
<input type="submit" name="sub">
</form>
</html>
<?php
if (isset($_REQUEST['sub'])) {
require_once ('start.php'); //Contains all database connections
$queryUser = $_REQUEST['urlid'];
echo($queryUser);
$result5 = runquery($queryUser); //Defined inside start.php
echo "<table border='1'>";
$i = 0;
while ($row = db2_fetch_assoc($result5)) {
if ($i == 0) {
foreach($row as $field => $value) {
echo "<th>".$field."</th>";
$i = $i + 1;
}
}
echo "<tr>";
foreach($row as $field => $value) {
echo "<td>".$value."</td>";
}
echo "</tr>";
}
echo "</table>";
$x = file_get_contents('test.sql');
$res = runquery($x);
$myfile = tmpfile();
$write = "";
while ($row = db2_fetch_assoc($res)) {
if ($i == 0) {
foreach($row as $field => $value) {
$write .= $field."\t";
$i = $i + 1;
}
$write .= "\n";
}
foreach($row as $field => $value) {
$write .= $value."\t";
}
$write .= "\n";
}
echo $write;
fwrite($myfile , $write);
fclose($myfile);
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=data.txt');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($myfile));
ob_clean();
flush();
readfile($myfile);
unlink($myfile);
}
?>
现在的问题是两者并没有同时发生。如果我注释掉了下载部分(从标题调用开始的部分),它将显示数据,但是如果我取消注释该部分,则它将仅下载一个空白文件,而不显示数据。
所以: