私は、MySQLデータベースからの結果を表示するPHPファイルを作成しました。
echo "<table><tr><td>";
...
echo "</td></tr></table>";
しかし、ここで、テーブルの下部に、作成したテーブルをHTML形式で保存する「レポートの保存」のようなボタンを作成したいと思います。
では、どのようにそれを行うことができますか?
次のスクリプトを使用できます。
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'];
}
?>
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);
?>