Put some unique tag where the keywords and metatags shoudl go, something you can str_replace later, like: <meta name="keywords" value="<I_WILL_REPLACE_THIS_META_KEYWORDS>" />
ob_start() before you do anything at all in the script.
At the end of the script, $contents_of_page = ob_get_contents() to get the output buffered HTML and PHP, and run a str_replace:
$contents_of_page = str_replace ("<I_WILL_REPLACE_THIS_META_KEYWORDS", $your_meta_keywords_variable, $contents_of_page);
print ($contents_of_page);
www.php.net/ob_start
www.php.net/ob_get_contents