You can use MVC style programming which separates every thing . But this is not recommended for small projects.
You should make sure all the processing takes place before all outputs. create template files and place holders for page info. Then every page will loads the place holder info to an array and fills it.