Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using include() within ob_start()

Tags:

php

Need a bit of PHP help here, the included content is appearing as '1' which means that its true but need it's contents to appear and im unsure why it isn't. Here is a shortened version of a function:

public function content {
    $website->content = 'Some content here. ';
    ob_start();
    include('myfile.php');
    $file_content = ob_end_clean();
    $website->content .= $file_content;
    $website->content .= ' Some more content here.';
     echo $website->content;
}

This outputs:

Some content here 
1 
Some more content here

When I need it to output:

Some content here
'Included file content here'
Some more content here

Any idea's how I can fix this?

like image 725
Chris Pynegar Avatar asked Dec 14 '11 19:12

Chris Pynegar


3 Answers

Try using ob_get_clean() instead of ob_end_clean().

Both clear the current buffer but ob_end_clean() returns a boolean, whereas ob_get_clean() returns the contents of the current buffer.

like image 113
donturner Avatar answered Sep 21 '22 18:09

donturner


Instead of using ob_end_clean modify your existing code into something similar to the below

ob_start();

include('myfile.php');

$file_content = ob_get_contents();

ob_end_clean ();

The reason I'm not voting for ob_get_clean is because I've had times when other developers get confused regarding what is really going on, the function name doesn't really state that the output buffering will end after it's call.

I think that function will be prone to further bugs, therefor using ob_start/ob_end_clean is easier to comprehend and better for future code maintenance.

The trade off between one extra line of code but easier code to understand is well worth it.

like image 43
Filip Roséen - refp Avatar answered Sep 20 '22 18:09

Filip Roséen - refp


You should be using ob_get_clean(), not ob_end_clean(). The former returns a string of the output buffer and empties it, while the latter just does the emptying and returns a bool.

like image 43
Tim Cooper Avatar answered Sep 17 '22 18:09

Tim Cooper