PHP捕获print/require变量输出

Pee*_*Haa 4 php

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

我有以下情况:

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

title.php

<?php

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

print($content);
Run Code Online (Sandbox Code Playgroud)

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

page.php文件

<?php

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

print($content);
Run Code Online (Sandbox Code Playgroud)

我有一个功能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);
}
Run Code Online (Sandbox Code Playgroud)

当我在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;
}
Run Code Online (Sandbox Code Playgroud)

Arn*_*anc 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()
Run Code Online (Sandbox Code Playgroud)

或者,请注意您还可以从包含的文件返回值,例如从函数中返回:

a.php只会:

return "<html>";
Run Code Online (Sandbox Code Playgroud)

b.php:

$html = include "a.php"; // $html will contain "<html>"
Run Code Online (Sandbox Code Playgroud)