I have a similar process to output all email addresses from the database into a downloadable txt file. It looks like this:
$xoutput = show_subscriber_list();
$xfile = fopen('xsubscriber.txt' , "w") or die("Unable to open file!");;
fwrite($xfile,$xoutput);
fclose($xfile);
$filename="xsubscriber.txt"; // of course find the exact filename....
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false); // required for certain browsers
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'. basename($filename) . '";');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
The show_subscriber_list
function does the SQL query of the data, getting all the data in a loop through the rows that are returned from the query. That function returns that data as a string, which is used as the content of the $filename
(as in return $text_data;
).
The $filename
is stored in the current folder. Then that $filename
is used in the $header stuff, which gives you the file as a download/open dialog.
The important part is to ‘build’ the contents of the file before you do the header stuff. You could just as easily ‘build’ the data into a string, then do the header stuff.
Added
Here is a function that returns the database contents as text. Called with
$data = mysqli_query($conn, $sql);
$output = display_data($data); // text output used in the above function
function display_data($data) {
$output = "";
foreach($data as $row) {
$output .= $row["email"] . PHP_EOL ;
}
return $output;
}
And note, as mentioned in comment from OP, that you need to set the proper Content-Type needed for your file contents; I have it set as a PDF.