PHP file_get_contents with php intact?

后端 未结 6 1246
后悔当初
后悔当初 2021-02-15 16:30

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

相关标签:
6条回答
  • 2021-02-15 16:48

    Write a function in the included PHP script that returns the desired output. Define a constant in the main PHP script. In the included PHP script, check for absence of said constant and echo the return value of the function if this is the case.

    0 讨论(0)
  • 2021-02-15 17:04

    Even though it is often purported to be evil, you could try using eval() along with get_file_contents()

    0 讨论(0)
  • 2021-02-15 17:07

    Doing the include into the loop is not SO dumb.

    All variables defined before the include will be accessible into your template.

    Keep it simple !

    == EDIT ==

    Or maybe you could 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 simple anymore ^^)

    0 讨论(0)
  • 2021-02-15 17:12

    If you're developing in 5.3 it's much easier but even on 5.2 you can use what's called an anonymous function to do this.

    An anonymous function will allow you to pass code around as a variable. To load this code from a file you may have to file_get_bytes into a string, eval that, then put in in a variable but you get the point I hope.

    5.3: Anonymous functions

    5.2: create_function

    0 讨论(0)
  • 2021-02-15 17:14

    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.

    0 讨论(0)
  • 2021-02-15 17:14

    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.

    0 讨论(0)
提交回复
热议问题