2011-01-25 70 views
3

是否可以将print()的输出添加到变量中?PHP捕获print/require变量输出

我有以下情况:

我有一个PHP文件,该文件看起来是这样的:

title.php

<?php 

$content = '<h1>Page heading</h1>'; 

print($content); 

我有一个PHP文件看起来像这样:

page.php

<?php 

$content = '<div id="top"></div>'; 
$content.= $this->renderHtml('title.php'); 

print($content); 

我有一个函数renderHtml()

public function renderHtml($name) { 
    $path = SITE_PATH . '/application/views/' . $name; 

    if (file_exists($path) == false) { 
     throw new Exception('View not found in '. $path); 
     return false; 
    } 

    require($path); 
} 

当我转储page.php文件不包含title.php内容的内容变量。 title.php的内容只是在调用时才打印,而不是添加到变量中。

我希望我很清楚自己想做什么。如果没有,我很抱歉,请告诉我你需要知道什么。 :)

感谢您的帮助!

PS

我发现已经有像我这样的问题了。但这是关于Zend FW的。

How to capture a Zend view output instead of actually outputting it

不过我想这正是我想做的事情。

我应该如何设置功能,使其表现如此?

编辑

只是想分享最终的解决方案:

public function renderHtml($name) { 
    $path = SITE_PATH . '/application/views/' . $name; 

    if (file_exists($path) == false) { 
     throw new Exception('View not found in '. $path); 
     return false; 
    } 

    ob_start(); 
    require($path); 
    $output = ob_get_clean(); 

    return $output; 
} 

回答

14

您可以捕获输出与ob_start()ob_get_clean()功能:

ob_start(); 
print("abc"); 
$output = ob_get_clean(); 
// $output contains everything outputed between ob_start() and ob_get_clean() 

另外,注意,你可以也从包含文件返回值,如函数:

a.php只会:

return "<html>"; 

b.php:

$html = include "a.php"; // $html will contain "<html>" 
+0

我将如何让renderHtml功能的方式,我可以使用:`$这个 - > renderHtml( 'page.php文件');`这样它会打印:`

页标题

` – PeeHaa 2011-01-25 20:07:52

+0

Nvm明白了!感谢用户! – PeeHaa 2011-01-25 20:09:51

2

您可以使用输出缓存来捕捉任何输出发送ob_start()​​。您使用ob_get_flush()http://us3.php.net/manual/en/function.ob-get-flush.php捕获输出。

或者你可以只返回标题的输出。PHP的,像这样:

<?php 

$content = '<h1>Page heading</h1>'; 
return $content;