How to make an included php file a variable
I would like to make a php file i have a part of a variable i'm building.
ie
$print = 'something';
$print .= incl开发者_如何学Cude('register_form.php');
print $print;
However this doesn't work. register_form.php will be not be included in the $print var, and will be echo'd out before the start of the print out.
Is there a way to achieve this?
I know I could go into register_form.php and make it all a function like register_form() and return its output, however, due to the way I've structured this (and i'm a bit of a newb) this would create more headaches then if I could merely do the above attempt.
Thanks for any pointers!
You can do this instead through output buffering.
ob_start();
include('register_form.php');
$print = ob_get_contents();
ob_end_clean();
echo $print;
Another option is file_get_contents($filename);
Reads the entire file into a string.
file_get_contents
--EDIT
Sorry, just read your question a bit more properly. Output buffing is about the only way to go if you have echo statements in your php form.
A cleaner way would be to have the output form functions return the HTML so you can choose when it's outputted. It maybe a small headache but will like a lot easier in the future.
Output buffering:
ob_start();
include('register_form.php');
$output = ob_get_clean();
echo $output;
Included files can have return values. By combining this with output buffering you can achieve exactly what you want.
register_form.php
ob_start();
// content
return ob_get_clean();
Then your code will work:
$print = 'something';
$print .= include 'register_form.php' ;
echo $print;
精彩评论