Jump to content

Php Function That Returns The Evaluated Code In A File?


omgRawr

Recommended Posts

I need a PHP function that evaluates the code in a file and returns it. Unfortunately I wasn't able to find one, and had to rely on output buffering to perform the task. Say if I wanted to evaluate the code in a file that contains both PHP and HTML code. This would be my method of doing it:

<?phpfunction eval_page($page){	if (file_exists($page)) 	{		 ob_start(); 		 include ($page); 		 		 return ob_get_clean(); 	}}?>

The code above basically includes a file so that the code in it can be parsed. The HTML output is stored in the output buffer and then I call ob_get_clean() to get the contents of the output buffer and clear it at the same time. Unfortunately this has some drawbacks though, and so I need a function that can do this but does not require the use of output buffering to perform the task. Does anyone know of another method?

Link to comment
Share on other sites

PHP has the eval() function, it evaluates strings as code.
$file = file_get_contents("file.php"); $return_value = eval($file);

That doesn't work. Eval only works with pure PHP code, which means that if HTML code is found, then eval will return an error. The files that I'm using have HTML code inside of them so that method won't work.
Link to comment
Share on other sites

For what it's worth, in my template system I use the output buffering method to include a file. If the include file sends output using the regular method eval won't be able to capture that, that's what output buffering is for. If you want to tailor your include files just to be used with eval then you would need to have the files return all of the output instead of printing it.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...