Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/247.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将文件包含到变量中_Php_Include_Server Side Includes - Fatal编程技术网

Php 将文件包含到变量中

Php 将文件包含到变量中,php,include,server-side-includes,Php,Include,Server Side Includes,我试图保持代码的整洁,将其中的一些代码分解成文件(有点像库)。但其中一些文件需要运行PHP 所以我想做的是: $include = include("file/path/include.php"); $array[] = array(key => $include); include("template.php"); 与template.php相比,我会: foreach($array as $a){ echo $a['key']; } 所以我想将php运行后发生的事情存储在

我试图保持代码的整洁,将其中的一些代码分解成文件(有点像库)。但其中一些文件需要运行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;
}

或者您的意思是为每个文件创建一个函数?

您的
文件/path/include.php的外观如何

您必须通过http调用
file\u get\u contents
,以获取其输出,例如

$str = file_get_contents('http://server.tld/file/path/include.php');
最好通过函数修改文件以输出一些文本:

<?php

function CreateOutput() {
  // ...
  return $output;
}

?>
似乎您需要使用--请特别参阅和函数

使用输出缓冲将允许您将标准输出重定向到内存,而不是将其发送到浏览器


下面是一个简单的例子:

// Activate output buffering => all that's echoed after goes to memory
ob_start();

// do some echoing -- that will go to the buffer
echo "hello %MARKER% !!!";

// get what was echoed to memory, and disables output buffering
$str = ob_get_clean();

// $str now contains what whas previously echoed
// you can work on $str

$new_str = str_replace('%MARKER%', 'World', $str);

// echo to the standard output (browser)
echo $new_str;
您将得到的输出是:

hello World !!!

所以如果我做了一个include而不是echo,然后ob_对一个变量进行了清理,它应该会工作吗?如果你包含了文件echo,它会得到缓冲——你将能够把它放到一个变量(希望我正确理解这个问题)@jefffan24,不,这不是我的意思,那会和以前完全一样。我的意思是直接在函数中执行文件$filename中的操作,并将其保存在变量$output中,然后将其发送回。要么一直使用变量,要么使用。很难说什么时候我们不知道你的文件和里面有什么,你到底在用php做什么。
hello World !!!