You can use the output buffer functions.
Just before the while(), put ob_start() and in the end of the loop, put $tofile = ob_get_contents();
And that goes to the file. You know, fopen() and fwrite()?
I'm feeling lazy, sorry.
code:
ob_start();
// while loop
$text = ob_get_contents();
$op = fopen($file,'w'); // or 'a' if you want to append it
fwrite($op, $text);
fclose($op);
I find that easier than putting variables all over the place.