Home » Php » php – Using include() within ob_start()

php – Using include() within ob_start()

Posted by: admin July 12, 2020 Leave a comment


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. ';
    $file_content = ob_end_clean();
    $website->content .= $file_content;
    $website->content .= ' Some more content here.';
     echo $website->content;

This outputs:

Some content here 
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?

How to&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.


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



$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.


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.