将PHP的print/require输出捕获到变量中

4

你能否将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的。 如何捕获Zend视图输出而不是实际输出 然而,我认为这正是我想做的。
我应该如何设置函数以使其像那样运行?
编辑
只是想分享最终的解决方案:
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个回答

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

我该如何编写renderHtml函数以便我可以使用$this->renderHtml('page.php');,以便它打印出<div id="top"></div><h1>Page heading</h1> - PeeHaa

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接