如何通过保存为按钮保存PHP的.html文件?

时间:2012-11-22 10:52:01

标签: php html save

我已经创建了一个PHP文件,它显示了MySQL数据库的结果,因为我们都在

中创建
echo "<table><tr><td>";
...
echo "</td></tr></table>";

但是现在我想在表格底部创建一个按钮,例如'save report',它将创建的表格保存为HTML格式。

那怎么可能呢?

2 个答案:

答案 0 :(得分:2)

您可以使用以下脚本:

<强>的index.php
在index.php中,您有HTML表。

<?php

$contents = "<table><tr><td>A</td><td>B</td></tr><tr><td>One</td><td>Two</td></tr><tr><td>Three</td><td>Four</td></tr></table>"; // Put here the source code of your table.

?>
<html>
    <head>
        <title>Save the file!</title>
    </head>
    <body>

        <?php echo $contents; ?>

        <form action="savefile.php" method="post">
            <input type="hidden" name="contents" value="<?php echo htmlspecialchars($contents); ?>">
            <input type="submit" value="Save file" />
        </form>
    </body>
</html>

<强> savefile.php
然后使用文件savefile.php弹出浏览器的下载对话框以保存文件。

<?php

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    header('Content-type: text/html');
    header('Content-Disposition: attachment; filename="table.html"');

    echo $_POST['contents'];
}

?>

答案 1 :(得分:1)

我认为你想将PHP / MySQL生成的报告保存为HTML文件吗?

<?php

// Open file for writing
$fileHandle = fopen("/DestinationPath/DestinationFile.html", "w");

// Dump File
$head = "<html><head><title>my reports</title></head><body>\n";
fwrite($fileHandle, $head);
$sql = mysql_query("Your sql query here");
while ($result = mysql_fetch_assoc($sql)) {
    $line = $result['yourmysqlfield']."\n";
    fwrite($fileHandle, $line);

}
$foot = "</body></html>\n";
fwrite($fileHandle, $foot);

// Close File
close($fileHandle);

?>
相关问题