I think you are looking for php buffers. ob_* will help you do that.
Check http://php.net/ob_start
template.php :
<html>
<head></head>
<body><?=$foo?></body>
</html>
index.php :
<?php
$foo = $_POST['text'];
ob_start();
include('template.php');
$template_html = ob_get_contents();
ob_end_clean();
//do your stuff
echo $template_html;
?>