gpt4 book ai didi

PHP Force 下载包括 HTML 源代码

转载 作者:行者123 更新时间:2023-11-28 01:31:13 24 4
gpt4 key购买 nike

我有一个表单,可以在点击提交按钮时对 mySQL 数据库运行查询。我想捕获该结果并强制用户下载文件。我一切正常,但正在下载的文件包含我的 HTML 页面的源代码。请注意,下面的代码在我的主索引文件中,因此它上面还有其他代码,例如 doctype、header、body 标签。

    <?php
# 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);
}
?>

最佳答案

如果您不需要 TXT 文件中的 html 代码(正文、标题...),则需要将此代码单独放在另一个文件中。

HTML代码:

<html>
<body>
<form action="downloadPage.php"></form>
</body>
</html>

PHP(下载页面.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);

?>

关于PHP Force 下载包括 HTML 源代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30204706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com