As opposed to using an include, which executes the included php in the file...is it possible to save the contents of a php file to a variable - but with the php still intact and executable?
My goal looks something like:
$template = some_imaginary_include_function('myfile.php');
foreach($list_of_blogs as $blog) {
// somehow get blog content in template and render template;
}
I know thats a dumb example...but I hope it illustrates the general idea. If I have to loop through the template 50 times on a page (say it is a list of blogs), it seems dumb to actually run and include for each.
Am I wrong? Is there a way to do this?
The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.
This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to length bytes. On failure, file_get_contents() will return false . file_get_contents() is the preferred way to read the contents of a file into a string.
They both read an entire file, but file reads the file into an array, while file_get_contents reads it into a string.
Curl is a much faster alternative to file_get_contents.
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 get whatever $file
is, and parse it with PHP, then return the output into a variable.
By using $content = file_get_contents('/path/to/your/file.php');
all the PHP tags will be preserved, you can then eval()
or tokenize
them to do whatever you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With