Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP file_get_contents with php intact?

Tags:

include

php

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?

like image 598
johnnietheblack Avatar asked Jan 13 '10 23:01

johnnietheblack


People also ask

What does file_get_contents do in PHP?

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.

What is the difference between the file () and file_get_contents () functions write with small program?

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.

What is the difference between file_get_contents () function and file () function?

They both read an entire file, but file reads the file into an array, while file_get_contents reads it into a string.

Is curl faster than file_get_contents?

Curl is a much faster alternative to file_get_contents.


2 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 get whatever $file is, and parse it with PHP, then return the output into a variable.

like image 190
alex Avatar answered Sep 30 '22 05:09

alex


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.

like image 31
Alix Axel Avatar answered Sep 30 '22 06:09

Alix Axel