views:

342

answers:

4

The following is not achieving what I desire

<?
echo ob_start() . "<br>";
echo "1x<br>";
echo ob_start() . "<br>";
echo "2x<br>";
echo ob_flush() . "<br>";
echo "3x<br>";
echo ob_flush() . "<br>";
?>

The output is the following

1
1x
1
2x
1
3x
1

I am wanting something along the lines of

1x
3x
2x

I assume the problem is its putting the output from the second ob_start() in the first output buffer. But how do I get my desired output?

Edit:

Basically what I am trying to achieve is providing the tag which needs to be in the head of a HTML document at a latter point in the output. Ie, half way through the script after it has already printed the docs head infomation it needs to then provide the .

+1  A: 

Why don't you just write

echo "1x"."<br>";
echo "3x"."<br>";
echo "2x"."<br>";
jitter
+2  A: 

Refer to the PHP manual for ob_start. You don't want to

echo ob_start();

because that function returns true or false, so it will output a 1 or 0 instead

ob_start();
echo "1x" . "<br />";
echo "2x" . "<br />";
echo "3x" . "<br />";
ob_flush();

Overall your objective isn't very clear. ob_start() is used for cleaning up a bunch of output before it is sent. It shouldn't be used as a stack.

Try SplStack if you want to use a stack in PHP.

Jack B Nimble
I know those function calls return 0 or 1. I was just printing them to prove they were being called correctly.
nullptr
+1  A: 

What about the following:

<?php
echo ob_start();
echo "1x<br>";
$keep_me_1 = ob_get_contents(); /* optional and for later use */
echo ob_flush();

echo ob_start();
echo "3x<br>";
$keep_me_2 = ob_get_contents(); /* optional and for later use  */
echo ob_flush();

echo ob_start();
echo "3x<br>";
$keep_me_3 = ob_get_contents(); /* optional and for later use  */
echo ob_flush();

?>

If you want to use more of the "stack" functionality you should take a look at ob_end_flush.

merkuro
This is how I actually did it. Very close to what you described however you need to call ob_clean() instead of ob_flush() ob_start();echo "1<br>";$g_ob[] = ob_get_contents();ob_clean();ob_start();echo "2<br>";$g_ob[] = ob_get_contents();ob_clean();ob_start();echo "3<br>";$g_ob[] = ob_get_contents();ob_clean();echo $g_ob[0];echo $g_ob[2];echo $g_ob[1];
nullptr
A: 

You can use ob_get_contents() to save the contents of the inner buffer to a string, then call ob_end_clean() to throw the contents away. Later, use a callback function in the outer buffer to write out the string.

UncleO