Home > code > PHP: Include File in a Variable

PHP: Include File in a Variable

php code 300x193 PHP: Include File in a Variable

Simply using include() or require() to output the contents of a ‘include’ file on another web page may work perfectly 90% of the time. However, there will be times where you may want to save it into a variable instead – especially if you are using PHP template classes to generate your web pages. Anyone trying to add a simple thing as a banner on popular forum scripts like phpBB and vBulletin will know what I mean. :grin:

Anyway, I will try to show you how you can do that using PHP’s ob_start(), ob_get_contents() and ob_end_clean().

//  Filename: INDEX.PHP
//  ==========================================

//  all the usual page and template code here
//  and where we want out 'include' variable to
//  appear, we add these lines

ob_start(); # start buffer
include_once( '/home/user/public_html/ad_table.php' );
# we pass the output to a variable
$html = ob_get_contents();
ob_end_clean(); # end buffer
# and here's our variable filled up with the html
echo $html;

//  we can then continue on with our web page and template
//  script or even add another 'include' variable!

ob_start();
require_once( '/home/user/public_html/ad_table2.php' );
$html2 = ob_get_contents();
ob_end_clean();
echo $html2;

if any one has any other great idea then comment it and let us know

Related Posts

  1. No comments yet.
  1. No trackbacks yet.