将文件包含到变量中
我试图保持我的代码干净,将其中一些分解成文件(有点像库)。但其中一些文件需要运行 PHP。
所以我想做的是这样的:
$include = include("file/path/include.php");
$array[] = array(key => $include);
include("template.php");
比在 template.php 中我会:
foreach($array as $a){
echo $a['key'];
}
所以我想将 php 运行后发生的事情存储在变量中以便稍后传递。
使用 file_get_contents 不会运行 php,它会将其存储为字符串,所以有什么选项可以做到这一点还是我运气不好?
更新:
就像:
function CreateOutput($filename) {
if(is_file($filename)){
file_get_contents($filename);
}
return $output;
}
或者您的意思是为每个文件创建一个函数?
I am trying to keep my code clean break up some of it into files (kind of like libraries). But some of those files are going to need to run PHP.
So what I want to do is something like:
$include = include("file/path/include.php");
$array[] = array(key => $include);
include("template.php");
Than in template.php I would have:
foreach($array as $a){
echo $a['key'];
}
So I want to store what happens after the php runs in a variable to pass on later.
Using file_get_contents doesn't run the php it stores it as a string so are there any options for this or am I out of luck?
UPDATE:
So like:
function CreateOutput($filename) {
if(is_file($filename)){
file_get_contents($filename);
}
return $output;
}
Or did you mean create a function for each file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来您需要使用
输出缓冲控制
-- 特别参见ob_start()
和ob_get_clean()
函数。使用输出缓冲将允许您将标准输出重定向到内存,而不是将其发送到浏览器。
Here's a quick example :
您将得到的输出是:
It seems you need to use
Output Buffering Control
-- see especially theob_start()
andob_get_clean()
functions.Using output buffering will allow you to redirect standard output to memory, instead of sending it to the browser.
Here's a quick example :
And the output you'll get is :
您的
file/path/include.php
是什么样子的?您必须通过http调用
file_get_contents
来获取它的输出,例如,最好修改您的文件以通过函数输出一些文本:
而不是在包含它之后,调用该函数来获取输出。
How does your
file/path/include.php
look like?You would have to call
file_get_contents
over http to get the output of it, e.g.It would be better to modify your file to output some text via a function:
Than after including it, call the function to get the output.