繁体   English   中英

如何在不重复的情况下在PHP中将echo存储在变量中?

[英]How to store echo in a variable in PHP without duplicating?

想象以下情况:

<?php
echo 'foo';
echo 'bar';
?>

简单吧? 现在,如果在这个简单脚本的结尾,我需要将我在脚本中回显的所有内容放在一个变量中,例如:

<?php
echo 'foo';
echo 'bar';
// $end // which contains 'foobar';
?>

我尝试了这个:

<?php
$end = NULL;
echo $end .= 'foo'; // this echoes foo
echo $end .= 'bar'; // this echoes foobar (this is bad)
// $end // which contains 'foobar' (this is ok);
?>

但是它不起作用,因为它附加了数据,因此回显了附加的数据(重复的)。 有什么办法吗?

编辑:我不能使用OB,因为我已经在脚本中以其他方式使用了OB(我正在浏览器中模拟CLI输出)。

显然我是在误解:所以我建议这样做:

<?php
    $somevar = '';
    function record_and_echo($msg,$record_var) {
        echo($msg);
        return ($msg);
    }
    $somevar .= record_and_echo('foo');
    //...whatever else//
    $somevar .= record_and_echo('bar');
?>

老:除非我误解了,否则就可以做到:

<?php
    $output = ''
    $output .= 'foo';
    $output .= 'bar';
    echo $output;
?>

我不太确定您要完成什么,但请考虑使用输出缓冲:

<?php
ob_start();
echo "foo";
echo "bar";

$end = ob_get_clean();
echo $end;

OB可以嵌套:

<?php
ob_start();

echo 'some output';

ob_start();

echo 'foo';
echo 'bar';

$nestedOb = ob_get_contents();
ob_end_clean();

echo 'other output';

$outerOb = ob_get_contents();
ob_end_clean();

echo 'Outer output: ' . $outerOb . '' . "\n" . 'Nested output: ' . $nestedOb;

结果:

Outer output: some outputother output;
Nested output: foobar

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM