在PHP中打开“另存为”对话框
我有一个文件,index2.php,它是通过表单写入的 我使用输出缓冲区将此文件的全部内容存储在变量在PHP中打开“另存为”对话框,php,Php,我有一个文件,index2.php,它是通过表单写入的 我使用输出缓冲区将此文件的全部内容存储在变量$final\u code中 现在,我想在页面的末尾添加一个“下载”按钮,它会弹出一个“另存为”对话框,允许用户将该文件的源代码(即变量)保存为.txt格式,但我被难倒了 index2.php: <?php // Start buffering the output ob_start(); ?> <!-- INDEX2.PHP HTML ELEMENTS HERE --&g
$final\u code
中
现在,我想在页面的末尾添加一个“下载”按钮,它会弹出一个“另存为”对话框,允许用户将该文件的源代码(即变量)保存为.txt格式,但我被难倒了
index2.php:
<?php
// Start buffering the output
ob_start();
?>
<!-- INDEX2.PHP HTML ELEMENTS HERE -->
<?php
// Store the contents of the buffer
$final_code = ob_get_contents();
// Print the contents of the buffer
ob_end_flush();
?>
<form action="savefile.php" method="post">
Happy? Save this to file: <input type="submit" name="savefile" value="Save" />
</form>
高兴吗?将此保存到文件:
我不确定是否需要将其写入此文件或savefile.php,因此后者当前为空。是否正在查找php下载脚本(从浏览器)?是否正在查找php下载脚本(从浏览器)?您需要使用标题强制下载:
$file = 'somefile.zip';
if(!file)
{
// File doesn't exist, output error
die('file not found');
}
else
{
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file);
}
示例取自:
有关更多说明,请参阅链接 您需要使用标题强制下载:
$file = 'somefile.zip';
if(!file)
{
// File doesn't exist, output error
die('file not found');
}
else
{
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file);
}
示例取自:
有关更多说明,请参阅链接 我认为您无法在浏览器中强制执行“另存为文件”对话框 为了强制下载txt文件,我执行以下操作:
header('Pragma: anytextexeptno-cache', true);
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: text/plain");
header("Content-Disposition: attachment; filename=\"example.txt\"");
echo $output;
希望对您有所帮助。我认为您无法在浏览器中强制执行“另存为文件”对话框 为了强制下载txt文件,我执行以下操作:
header('Pragma: anytextexeptno-cache', true);
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: text/plain");
header("Content-Disposition: attachment; filename=\"example.txt\"");
echo $output;
希望对您有所帮助。请参阅如何在该文件中获取我的变量
$final\u code
的内容?谢谢。这给了我一个“压缩(压缩)文件夹无效或损坏。”错误-它也在index2.php页面加载上运行,而不是在单击按钮时运行…我是否应该通过隐藏表单输入将所有代码移动到savefile.php,在使用$final_code变量之前,请将其张贴在此处?如果您试图保存的是文本文件,则需要更改文件名($file)和内容类型以匹配此文件。内容类型应为text/plain
。如何获取此文件中我的变量$final\u code
的内容?谢谢。这给了我一个“压缩(压缩)文件夹无效或损坏。”错误-它也在index2.php页面加载上运行,而不是在单击按钮时运行…我是否应该通过隐藏表单输入将所有代码移动到savefile.php,在使用$final_code变量之前,请将其张贴在此处?如果您试图保存的是文本文件,则需要更改文件名($file)和内容类型以匹配此文件。内容类型应为text/plain
。