PHP捕获变量中的打印/要求输出 [英] PHP capture print/require output in variable

查看:75
本文介绍了PHP捕获变量中的打印/要求输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to add the output of print() to a variable?

我有以下情况:

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

I have a php file which looks something like this:

title.php

<?php

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

print($content);

我有一个如下所示的php文件:

I have a php file which looks like this:

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的内容只是在调用时打印,而不是添加到变量中.

When I dump the content variable in page.php it doesn't contain the content of title.php. The content of title.php is just printed when it is called instead of added to the variable.

我希望我正在尝试做的事情很清楚.如果没有,我很抱歉,请告诉我您需要知道的内容. :)

I hope it is clear what I am trying to do. If not I'm sorry and please tell me what you need to know. :)

感谢您的所有帮助!

PS

我发现已经存在像我这样的问题.但这是关于Zend FW的.

I have found that there was already a question like mine. But it was regarding the Zend FW.

如何捕获Zend查看输出而不是实际输出

但是我认为这正是我想要做的.

However I think this is exactly what I want to do.

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

How should I setup the function so that it behaves like that?

编辑

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

Just wanted to share the final solution:

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;
}

推荐答案

您可以使用 ob_start() ob_get_clean() 函数:

You can capture output with the ob_start() and ob_get_clean() functions:

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

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

Alternatively, note that you can also return values from an included file, like from functions:

a.php:

return "<html>";

b.php:

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

这篇关于PHP捕获变量中的打印/要求输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆