Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ob_start() within a loop

I've got a problem when looping using foreach() loop and inside of this loop using ob_start() and ob_get_clean().

Here's my function:

protected function renderEmail() {
$template = $this->_case.".php";
if(is_file($this->_dir.DS.$template)) {
    ob_start();
    if(!empty($this->_records)) {               
        foreach($this->_records as $key => $value) {
            ${$key} = $value;
        }
    }
    require_once($this->_dir.DS.$template);
    return ob_get_clean();
} else {
    $this->_errors[] = "Email template not found";
    return false;
} }

This function is basically generating content of the email and then returns it.

The problem I have is when I loop through a number of email addresses - to send the same email content - only the first one returns the content - the following ones are blank - any idea why?

like image 408
user398341 Avatar asked Nov 03 '10 13:11

user398341


People also ask

What does Ob_start () function do?

The ob_start() function creates an output buffer. A callback function can be passed in to do processing on the contents of the buffer before it gets flushed from the buffer. Flags can be used to permit or restrict what the buffer is able to do.

What is Ob_start () and Ob_end_flush () in PHP?

While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush().

Should I use Ob_start?

Using ob_start allows you to keep the content in a server-side buffer until you are ready to display it. This is commonly used to so that pages can send headers 'after' they've 'sent' some content already (ie, deciding to redirect half way through rendering a page). Save this answer.


2 Answers

Ok - you won't believe - once I've posted this question - straight after I've realised where the problem was - I'm using require_once() function - which prevents the same file to be included again - once changed to include() everything works fine!

like image 121
user398341 Avatar answered Sep 19 '22 07:09

user398341


Every time you are going to use a same file several times inside a loop, you should never user require_once() or include_once, instead use, 'include', and everything will be fine!

like image 39
yunieski dieguez garcia Avatar answered Sep 18 '22 07:09

yunieski dieguez garcia