How to Parse an include file and Store the result in a Variable with PHP

Use of include is very common in PHP. include will parse a file and display the result. But, how to store the result in a variable for later use? In other words, how to load a php file into a variable?

This example will parse /path/to/include.php and store the result into variable $res

ob_start(); // turn on output buffering
$res = ob_get_contents(); // get the contents of the output buffer
ob_end_clean(); //  clean (erase) the output buffer and turn off output buffering


You could use:

$res = file_get_contents('http://your_server/path/to/include.php');

This method needs ‘allow_url_fopen = On’ which is a security risk. AVOID this method and keep allow_url_fopen = Off. Moreover, in PHP6, allow_url_fopen will no longer exist.


From PHP manual

Your comments are welcome!

MediSign - EHR for Small Medical Practices

EHR for Small Medical Practices

Medical records. Appointments. Electronic invoicing.