Friday, November 14, 2008

PHP: parsing an include

If you're using php include a fair amount, you may well get to a point where you don't just want to 'drop' some text into your document but need to resolve variables etc.

There is a written function in the php manual that allows 'included' php to be parsed - hopefully this post will make the code snippet slightly more visible to someone and hence save them some time: (from http://www.php.net/include/)

 
$string = get_include_contents('somefile.php');

function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return false;
}

?>


If you use this block of code, you can pass in the name of a file to be included and the resultant page will return with any php processing fully parsed (rather than being dumped out into the content of the page as static strings.

1 comments:

gary said...

Thanks Alex. That came in handy as I had just the situation you describe and I didn't find this in the manual.

Blog Archive

About Me