PHP捕获print / require变量输出

时间:2011-01-25 19:51:41

标签: php

是否可以将print()的输出添加到变量?

我有以下情况:

我有一个看起来像这样的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;
}

2 个答案:

答案 0 :(得分:15)

您可以使用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>"

答案 1 :(得分:2)

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

或者您可以像这样返回title.php的输出:

<?php

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