I have a form which runs a query against a mySQL database upon hitting the submit button. I want to capture that result result and force the user to download a file. I got everything working but the file being downloaded includes the source code of my HTML page. Note that the code below is within my main index file so it has other code above it such as the doctype, header, body tags.
我有一個表單,在點擊提交按鈕時對mySQL數據庫運行查詢。我想捕獲結果結果並強制用戶下載文件。我得到了一切,但正在下載的文件包含我的HTML頁面的源代碼。請注意,下面的代碼在我的主索引文件中,因此它上面有其他代碼,例如doctype,header,body標簽。
# Convert result to csv and push use to download if user pressed "Download" button
if(isset($_POST["downloadquery"])) {
$fp = fopen('php://output', 'w');
ob_start();
if ($fp && $result) {
fputcsv($fp, $headers); # populate header
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row)); #populate rows
}
}
$content = ob_get_clean();
$filename ='queryResults' . date('Ymd');
// Output CSV-specific headers
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '.txt";');
exit($content);
}
?>
1 个解决方案
#1
If you don't need of the html code (body, headers, ...) in TXT file, you need separate this code in another file.
如果您不需要TXT文件中的html代碼(正文,標題,...),則需要在另一個文件中單獨使用此代碼。
Html code:
PHP (downloadPage.php):
$fp = fopen('php://output', 'w');
ob_start();
if ($fp && $result) {
fputcsv($fp, $headers); # populate header
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row)); #populate rows
}
}
$content = ob_get_clean();
$filename ='queryResults' . date('Ymd');
// Output CSV-specific headers
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '.txt";');
exit($content);
?>