PHP file_get_contents with php intact?

Unlike using include, which executes the included php in the file ... is it possible to save the contents of the php file in a variable - but with php still intact and executable?

My goal is something like this:

$template = some_imaginary_include_function('myfile.php'); foreach($list_of_blogs as $blog) { // somehow get blog content in template and render template; } 

I know this is a dumb example ... but I hope this illustrates the general idea. If I need to go through the template 50 times on the page (let's say this is a list of blogs), it seems that it does not work and turns on for everyone.

Am I really wrong? Is there any way to do this?

+6
include php
source share
6 answers

How about this ...

 function getTemplate($file) { ob_start(); // start output buffer include $file; $template = ob_get_contents(); // get contents of buffer ob_end_clean(); return $template; } 

Basically, this will cause $file , and parse it using PHP, and then return the result to a variable.

+16
source share

Using $content = file_get_contents('/path/to/your/file.php'); , all PHP tags will be saved, you can eval() or tokenize them what you want.

+4
source share

Doing looping is not so stupid.

All variables defined before inclusion will be available in your template.

Keep it simple!

== EDIT ==

Or maybe you can improve alex's answer:

 function getTemplate($file, $template_params = array()) { ob_start(); // start output buffer extract($template_params); // see PHPDoc // from here $var1 will be accessible with value "value1" // so your template may contain references to $var1 include $file; $template = ob_get_contents(); // get contents of buffer ob_end_clean(); return $template; } echo getTemplate('your_template.php', array('var1' => 'value1')); 

(Not so easy anymore ^^)

+1
source share

Write a function in the included PHP script that returns the desired result. Define a constant in the main PHP script. In the included PHP script, check for the absence of the specified constant and echo the value of the function, if so.

0
source share

Although this is often called evil, you can try eval () along with get_file_contents()

0
source share

If you are developing in 5.3, this is much simpler, but even in 5.2 you can use what is called an anonymous function to do this.

An anonymous function allows you to pass code as a variable. To load this code from a file, you may need file_get_bytes in a string, eval, and then enter a variable, but you will get what I hope.

5.3: Anonymous Functions

5.2: create_function

0
source share

All Articles