So, if I understood correctly, you want to get some data from the database into a txt file to load it, right?
Well, the first thing you want to do is to generate this data file, there are several ways to do it, but since the file can be generated each time with different data, IMHO you need to generate and submit it on the fly, and for this you only need to create a separate php script to get the data and set the appropriate headers for it.
header("Content-type: text/plain"); //File type header("Content-Disposition: attachment; filename=SomeFileName.txt"); //suggested file name
After that, just use the printout of all the necessary data in a text file. eg.
<?php header("Content-type: text/plain"); //File type header("Content-Disposition: attachment; filename=SomeFileName.txt"); print "hey I'm a text file!";
will create the following.



Now, if you want to use jQuery, you can simply download it, mainly because depending on the browser, the file may get rendered.
So just name it in another window, like.
$('#foo').attr({target: '_blank', href : 'genfile.php'});
EDIT: I almost forgot ... Consider modifying your php code, its hints for SQL injections, as well as its bad practice for outputting html directly to php, this makes the code confusing, it's better to create an object, array or something also pass it a script to display it somewhere else.
EDIT 2 From the top of your head, create print_text.php with the correct headers and just
print $_POST["print"];
Then create a hidden form on your web page.
<form id="to_print" action="print_text.php" method="post" target="_blank"> <input id="print_data" name="parameter" type="hidden" value="None"> </form>
Then in your button, activate this:
$('#print_data').val($("#where_ever_your_content_is").text()); $('#to_print').submit();
This will send the form and open it in a new window. PHP will create a file with any text that you pass to it.
