you might want to read here to see if this is what you are looking for, though in not sure if this is your final intent: [man]ob_start[/man]
these functions can store your output into a buffer instead of printing it directly to the screen/response ... then at the end of the script you
1) save the output into your file on the server
2) print the output string so it gets to the users browser