php force download,PHP Force下載包括HTML源代碼

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);

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值