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

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

问题描述

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

但是主PHP模板本身中包含include();require_once();,并且替换单词之后保存的文件不会加载从主模板调用的文件.

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

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

解决方案

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.

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

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(); ?

解决方案

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/

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

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