I have much easier solution for you - it is simple! Just add this command at the very start of the php source:
ob_start();
This will start buffering the output, so that nothing is really output until the PHP script ends (or until you flush the buffer manually) - and also no headers are sent until that time!
So you don't need to reorganize your code, just add this line at the very beginning of your code and that's it :-)