PHP捕获变量中的打印/要求输出

编程入门 行业动态 更新时间:2024-10-25 07:32:56
本文介绍了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捕获变量中的打印/要求输出

本文发布于:2023-07-05 06:53:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1034356.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!