繁体   English   中英

PHP将浏览器输出保存为文件而不保存服务器上的文件

[英]PHP save browser output as file without saving file on server

我正在尝试创建链接以将浏览器输出保存为文件,而无需在服务器上创建文件。

这是我到目前为止所得到的:

<?php
ob_start();
?>

<html>
    webpage content
</html>

<?php
$page = ob_get_contents();
ob_end_flush();

$file= time().'.html';

file_put_contents($file, $page);
ob_start();
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
ob_end_flush();
?>

<a href="<?php echo $file; ?>.php">Download output as file</a>

如何在服务器上创建这样的链接WITHOUT SAVING文件?

感谢您的建议/想法/代码。

为什么那么复杂? 直接做到:

<?php
  header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment; filename="'.time().'.html"');
?>
<html>
    webpage content
</html>

你有两个相当简单的选择(还有其他选项,但它们会更复杂):

选项1,使用数据网址:

$pageData = base64_encode($page);
$finfo = new finfo(FILEINFO_MIME);
$pageDataMime = $finfo->buffer($page);
$pageDataURL = 'data:' . $pageDataMime .  ';base64,'.$pageData;
?>

<a href="<?php echo $pageDataURL; ?>.php">Download output as file</a>

选项2,使用查询字符串确定是否应下载输出:

if($_GET['download_data']) {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Content-Length: ' . filesize($file));
    echo $page;
    exit();
} else {
    // Output HTML as normal, including:
    <a href="<?php echo $normalPageURL ?>?download_data=1">Download output as file</a>
}

只需回显$ page:

<?php
ob_start();
?>

<html>
    webpage content
</html>

<?php
$page = ob_get_contents();
ob_end_flush();

$file= time().'.html';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . strlen($page));
echo $page;
?>

打开像fopen('php://output', 'w');这样的文件句柄fopen('php://output', 'w'); 并输出到它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM