PHP: file_get_contents 包含包含() 的 PHP 文件; [英] PHP: file_get_contents a PHP file with include();

查看:29
本文介绍了PHP: file_get_contents 包含包含() 的 PHP 文件;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

但是主PHP模板本身有 include();require_once(); 并且替换单词后保存的文件不会加载调用的文件来自主模板.

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.

保存文件的HTML源代码为 在其中,但不是 file_here 的输出——参见图片.

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.

如何调用 file_get_contents();仍然让主模板执行 include();或 require_once();?

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

推荐答案

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

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).

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

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).

如果您需要在打印之前处理其内容,请使用 ob_* 函数来操作 PHP 输出缓冲区.请参阅:https://www.php.net/manual/en/ref.outcontrol.php

If you need to work with its content before you print it, use ob_* functions to manipulate the PHP output buffer. See : 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/

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/

这篇关于PHP: file_get_contents 包含包含() 的 PHP 文件;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆