PHP: file_get_contents a PHP file with include();

白昼怎懂夜的黑 提交于 2020-03-16 05:27:47

问题


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 as another PHP in a directory.

But the master PHP template itself has include(); and require_once(); in it and the saved file after replacing the words doesn't load the files called from the master template.

The HTML source code of the saved file is with <?php include('file_here'); ?> in it, but not with the output of file_here -- see image.

How can I call file_get_contents(); and still let the master template execute include(); or require_once(); ?


回答1:


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/



来源:https://stackoverflow.com/questions/18190386/php-file-get-contents-a-php-file-with-include

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!