I mean that to test this, you need full access to your server: change the PHP code (such as adding echo statements like I did, and then actually fixing the code) and looking at what happens when you run it. Just looking at the PHP code doesn't help because it looks fine, but clearly something in the actual process of generating html is wrong-- so you need to have access to test it.
I still suggest that you compare your desired output to the real output and take it on step at a time. It's likely that there are a number of problems, but trying to fix them all at once will be confusing. Just do one at a time and figure out specifically what is not happening. PHP doesn't do anything mysterious: it operates line by line. And to debug it, you will need to operate line by line as well-- think like the program and go step by step to find out where it's wrong. Using tricks like "echo" above will help because you can check that at a certain point it's still correct (or incorrect).

