6

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.

enter image description here

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

4

1 回答 1

11

file_get_contents()将获取文件的内容,而不是将其作为 PHP 脚本执行。如果您希望执行这段代码,您需要包含它或处理它(例如,通过对 Apache 的 HTTP 请求)。

如果您包含此文件,它将作为 PHP 代码处理,当然,打印您的 HTML 标记(include*可以采用任何类型的文件)。

如果您需要在打印之前处理其内容,请使用ob_*函数来操作 PHP 输出缓冲区。请参阅:https ://www.php.net/manual/en/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.

顺便说一句,这种机制对于模板引擎来说听起来很沉重。基本上,模板不应包含 PHP 代码。如果您想要这种行为,请查看 Twig:http ://twig.sensiolabs.org/

于 2013-08-12T15:09:47.390 回答