2011-04-16 83 views
3

是否有可能需要一个PHP文件,并获得所有的回声被返回并存储到一个变量?PHP需要返回回声?

例子:

//file1.php 
// let's say $somevar = "hello world" 
<p><?php echo $somevar; ?></p> 


//file2.php 
$file1 = getEchoed("file1.php"); 
// I know getEchoed don't exist, but i'm unsure how to do it. 
+0

可能重复http://stackoverflow.com/questions/1814182/get-the-results-of- an-include-in-a-string-in-php) – mario 2011-04-16 23:58:00

回答

10

使用输出缓冲:

ob_start(); 
require('somefile.php'); 
$data = ob_get_clean(); 
+0

oops,将其更改为使用正确的功能。总是混淆这两者。 – ThiefMaster 2011-04-17 00:06:09

+0

如果我想关闭它,是否还需要ob_end()以及? – Pwnna 2011-04-17 14:05:21

+0

编号'ob_get_clean()实质上执行ob_get_contents()和ob_end_clean()。'' – ThiefMaster 2011-04-17 14:15:10

1

Output buffering可以做你的需要。

ob_start(); 
require("file1.php"); 
$file1 = ob_get_contents(); 
ob_clean(); 
1
ob_start(); 
include('file1.php'); 
$contents = ob_get_clean(); 

从file1.php输出现在存储在变量$内容。

0

Output buffering

<?php 

ob_start(); 

require 'file1.php'; 

$var_buffer = ob_get_contents(); 

ob_end_clean(); 

echo $var_buffer; 

?> 
的[?得到的结果在PHP中的字符串包含(