I would like to comment on this approach
As far as possible try to modularize your approach as there are so many advantages over something that achieves in a single shot
ease of maintenance
re usability
easy to debug
no need to test the entire application if its properly modularized
and of course, nobody would curse you if somebody else has to maintain your code
for your problem you could modularize it something like
( what I post is just an example )
fetching data from db into a file
processing the data from the file
redirecting output
now the problem space is broken down easily and you could easily challenge any of the module if there is a problem.
I have burnt my fingers many times since I don't have the habit of modularizing the code and I end up writing the same code again, do the same testing again, same debugging again.
I have to admit - its a shame !
Waste of time for which I had already wasted.
Just thought of sharing this