I need to give the user the option to save the result of a query in a text file and download it.
Now, I have this code:
while ($row = mysqli_fetch_array($resulta)){
echo "<tr>";
echo "<td class='cell0'><a href='Visualizar_Disciplina.php?nome=" .$row['nome'] . "'>" . $row['nome'] . " </a></td>";
echo "<td class='cell0'>" . $row['nomeprofessor'] . "</td>";
echo "<td class='cell0'>" . $row['creditos'] . "</td>";
echo "</tr>";
}
And I don't know what should I do to create the text file in the server and then, when the user hit a button, the file will be downloaded.
How can I do that?
Thanks!
You basically have two alternatives.
Alternative 1
Store the file on the server, and make sure the user can access the raw file via some URL. You probably want to have some logic for cleaning up files as each new download would add a new file on the server, which eventually will run out of space.
<?php
$uri = tempnam("/dir/for/files");
$myfile = fopen($uri, "w") or die("Unable to open file!");
while ($row = mysqli_fetch_array($resulta)){
$out = "<tr>
";
$out .= "<td class='cell0'><a href='Visualizar_Disciplina.php?nome=" .$row['nome'] . "'>" . $row['nome'] . " </a></td>
";
$out .= "<td class='cell0'>" . $row['nomeprofessor'] . "</td>
";
$out .= "<td class='cell0'>" . $row['creditos'] . "</td>
";
$out .= "</tr>
";
fwrite($myfile, $out);
}
fclose($myfile);
?>
Now the file is written to the server and you can point your client to the url corresponding to that file.
Alternative 2
Place a download.php file somewhere that will "generate" the content to be downloaded on the fly. In order for the browser of your user to accept the file as a download rather then as displayable content you need to set the appropriate headers at the top of download.php
<?php
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="filename.txt"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
while ($row = mysqli_fetch_array($resulta)){
echo "<tr>
";
echo "<td class='cell0'><a href='Visualizar_Disciplina.php?nome=" .$row['nome'] . "'>" . $row['nome'] . " </a></td>
";
echo "<td class='cell0'>" . $row['nomeprofessor'] . "</td>
";
echo "<td class='cell0'>" . $row['creditos'] . "</td>
";
echo "</tr>
";
}
exit;
?>