【发布时间】:2013-08-11 04:48:38
【问题描述】:
我需要直接在页面上编写和创建一个 .html 文件,然后让用户将其下载到他的本地计算机上。 .html 文件将包含来自数据库请求的完整操作系统信息。 它看起来像这样:
<?php
$content = "<!DOCTYPE html><html lang="en"><head></head><body>";
$content .= "<div>Hello World</div>";
$content .= get_all_contents_from_db();
$content .= "</body></html>";
?>
我看到了一个代码,可让您将所看到的页面下载到包含此代码的文件中:
<?php
if(isset($_POST['download']))
{
header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($File));
header("Connection: close");
}
?>
So the question is: How do I create a downloadable html file using php?
**PART 2**
<form method="POST" action=''>
<button name="download">Download File</button>
</form>
<?php
$content = "<!DOCTYPE html><html lang=\"en\"><head></head><body>";
$content .= "<div>Hello World</div>";
$content .= "</body></html>";
if(isset($_POST['download'])){
echo $content;
header("Content-Disposition: attachment; filename=\"slideshow.html\"");
header("Content-Length: " . filesize($content));
echo $content;
}
?>
输出
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<div class="main">Dashboard</br>
<form method="POST" action=''>
<button name="download">Download File</button>
</form>
<!DOCTYPE html><html lang="en"><head></head><body><div>Hello World</div></body></html><!DOCTYPE html><html lang="en"><head></head><body><div>Hello World</div></body></html> </div>
</div>
</body>
</html>
【问题讨论】:
-
你的问题缺少问题。
-
另外,
application/force-download是不存在的内容类型。 -
HTML 文档的 Content-type 是
text/html。 -
application/force-download可能是不存在的内容类型,但已被用作黑客;参见例如stackoverflow.com/a/10616753/469210 -
您不需要使用 hack。这就是 Content-Disposition 的用途。