PHP: file_get_contents a PHP file with include();

前端 未结 1 1597
渐次进展
渐次进展 2021-01-18 17:52

I have a PHP Script that calls a master PHP template (acts as HTML template) with file_get_contents, replaces a few words from it and then saves the final file

相关标签:
1条回答
  • 2021-01-18 18:30

    file_get_contents() will get the content of a file, not execute it as a PHP script. If you want this piece of code to be executed, you need to either include it, or process it (through an HTTP request to Apache, for instance).

    If you include this file, it'll be processed as PHP code, and of course, print your HTML tags (include* can take any kind of file).

    If you need to work with its content before you print it, use ob_* functions to manipulate the PHP output buffer. See : http://www.php.net/manual/fr/ref.outcontrol.php

    ob_start(); // Start output buffer capture.
    include("yourtemplate.php"); // Include your template.
    $output = ob_get_contents(); // This contains the output of yourtemplate.php
    // Manipulate $output...
    ob_end_clean(); // Clear the buffer.
    echo $output; // Print everything.
    

    By the way, such mechanism sounds heavy for a template engine. Basically, templates should not contain PHP code. If you want such behavior, have a look at Twig : http://twig.sensiolabs.org/

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