简体   繁体   中英

how to save .html file by PHP by save as button?

I've created a PHP file which shows the results from a MySQL database as we all create like in

echo "<table><tr><td>";
...
echo "</td></tr></table>";

But now I want to make a button at the bottom of the table, something like 'save report' , which saves the created table into HTML format.

So how could it be done?

You can use the following scripts:

index.php
In index.php, you have the HTML table.

<?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
And then use the file savefile.php to popup your browser's download dialog to save the file.

<?php

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

    echo $_POST['contents'];
}

?>

I think you want to save reports generated by PHP/MySQL as HTML file?

<?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);

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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