Include a file and store contents to variable

This very handy feature of PHP which allows you to include a file but store the contents of the included file to a variable. This is particularly useful for PHP scripts and software which output content to a page by using variables. Many CMSs are built like this.

The principal behind this solution is to use an output buffer. You start the output buffer, include the file(s), store the included content to a variable, then stop the output buffer. Code is shown below:

ob_start(); // start buffer
include (“file-to-include.php”);
$content = ob_get_contents(); // assign buffer contents to variable
ob_end_clean(); // end buffer and remove buffer contents
echo $content;

Permanent link to this article: https://blog.openshell.in/2011/04/include-a-file-and-store-contents-to-variable/

Leave a Reply

Your email address will not be published.