You could probably do that with
// top of script
ob_start();
//do all your stuff
//get the output (i.e. the html which shows up on the page) into a variable
$contents = ob_get_contents();
//do your database indexing here
//display the output
ob_end_flush();
//end script
I haven't tried this, but in theory it should work.
Cheers,
Alex ...