Yeah, use output buffering:
ob_start();
print_r($foo);
$bar = ob_get_contents();
ob_end_clean();
That will store the output of print_r($foo) to the string variable $bar rather than printing it to the script's output.
As for your other problem, I have no clue.