tags:

views:

62

answers:

2

how can i put the result of an include into a php variable?

I tried file_get_contents but it gave me the actual php code, whereas I want whats echoed.

+4  A: 

Either capture anything that's printed in the include file through output buffering

ob_start();
include 'yourFile.php';
$out = ob_get_contents();
ob_end_clean();

or alternatively, set a return value in the script, e.g.

// included script
return 'foo';
// somewhere else
$foo = include 'yourFile.php';

See Example 5 of http://de2.php.net/manual/en/function.include.php

Gordon
Also interesting to note that [ob_start()](http://us2.php.net/manual/en/function.ob-start.php) accepts a callback argument. (It took me a while to notice.)
Adam Backstrom
+2  A: 

or simply return a value from an included file as explained here.

return.php:
<?php

$var = 'PHP';

return $var;

?>


$foo = include 'return.php';

echo $foo; // prints 'PHP'
Ken