php html json escape | browser detection in javascript | auto comments in fb post
 


 

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

<?php
ob_start(); // turn on output buffering
include('/path/to/include.php');
$res = ob_get_contents(); // get the contents of the output buffer
ob_end_clean(); //  clean (erase) the output buffer and turn off output buffering
?>

Remarks

You could use:

<?php
$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.

References

From PHP manual

Hope to find it helpful. Your comments are welcomed!

Εγγραφή!
Sign-up for our free email newsletter. Get updates when new tutorials and tips are published. You can unsubscribe anytime with a click.

Your comments are welcomed!

This site actively encourages commenting on any post. Comments are not pre-moderated, but this community does not tolerate direct or indirect attacks, name-calling or insults. Please, read terms of use and Comment Policy at privacy policy.

More tips