PHP:file_get_contents一个包含include()的PHP文件;

Lee*_*Lee 4 php include file-get-contents

我有一个PHP脚本,它使用调用主PHP模板(充当HTML模板)file_get_contents,从中替换了几个字,然后将最终文件另存为另一个PHP在目录中。

但是主PHP模板本身具有include();且require_once();在其中,替换单词后保存的文件不会加载从主模板调用的文件。

保存的文件的HTML源代码包含<?php include('file_here'); ?>在其中,但file_here的输出不包含它-请参见图像。

在此处输入图片说明

我怎样才能调用file_get_contents(); 仍然让主模板执行include(); 或require_once(); ?

Joh*_*ith 9

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

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

如果需要在打印之前处理其内容,请使用ob_*函数来操纵PHP输出缓冲区。参见: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.
Run Code Online (Sandbox Code Playgroud)

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