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(). Let's look at our little include banner / ad file first.

Our sample include file - ad_table.php

This fictitious file we create will output one table with 3 rows of text ads. The entire sample file's code may look something like this:



//  Filename: AD_TABLE.PHP 
//  ======================
echo "<table>\n";
for( $i=0;$i<3;$i++ )
  echo "  <tr>\n";
  echo '    <td>'.get_ads('Text',$i+1)."</td>\n";
  echo "  </tr>\n";
echo '</table>';

//  ===================
//  ===================
function get_ads($keyword,$number)
  echo $keyword.' No.'.$number;

When we view the source / HTML of this particular page off a browser, it may look something like this:

    <td>Text No.1</td>
    <td>Text No.2</td>
    <td>Text No.3</td>

Using our 'include' variable in a web page

Now that we've seen our 'include' file and what it will output, we can then use our ad_table.php in any other web page (most likely in our template-script-driven web pages that is) simply by adding these lines of code:


//  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!

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


This is exactly what I did to add those text advertisements at the top of each page in GIDForums™.


How old are you?


 20 something

 30 something

 40 something

 Over 50