faqts : Computers : Programming : Languages : PHP : Common Problems : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

6 of 7 people (86%) answered Yes
Recently 6 of 7 people (86%) answered Yes

Entry

I want "include" to return a string instead of writing directly into the page.

May 7th, 2005 21:26
Prontex Design, Trevor Florence, http://www.php.net/include#AEN4968


A call to include() will return the value of the return statement 
contained within the file.
Basic Example (slightly simplified version from php.net):
return.php
<?php
$var = 'PHP';
return $var;
?>
test.php
<?php
$foo = include 'return.php';
echo $foo; // prints 'PHP'
?>
-----
If you want to return all the output from the included file and return 
it instead of writing directly into the page, you could use an output 
buffer to capture everything.
Example:
return.php
<?php
ob_start(); // Starts capture
// ...do any PHP as normal...
echo 'This Will Be Returned ';
echo 'To test.php';
$var = ob_get_contents(); // Gets the contents of the output buffer
ob_end_clean(); // Ends capture and cleans the buffer so that it will 
not be displayed
return $var;
?>
test.php
<?php
$foo = include 'return.php';
echo strtolower($foo); // prints 'this will be returned to test.php'
?>
-----
Another method that is essentially the same, but may be easier to 
understand is to skip "returning" the value with include, and just use 
the output buffer directly.
file.php
<?php
// ...do any PHP as normal...
echo 'This Will Be Returned ';
echo 'To test.php';
?>
test.php
<?php
ob_start(); // Starts capture
include 'file.php';
$foo = ob_get_contents(); // Gets the contents of the output buffer
ob_end_clean(); // Ends capture and cleans the buffer so that it will 
not be displayed
echo strtolower($foo); // prints 'this will be returned to test.php'
?>
More Information: 
http://www.php.net/include#AEN4968
http://www.php.net/ob_start