ob_start() within a loop
Asked Answered
T

3

8

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?

Treva answered 3/11, 2010 at 13:12 Comment(0)
T
23

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!

Treva answered 3/11, 2010 at 13:17 Comment(2)
Same here, pfff. So thnx for not deleting the question :)Almeda
The same... Lol :)))Reginareginald
C
3

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!

Cute answered 10/3, 2018 at 20:59 Comment(0)
M
0

Why looping?

extract($this->_records);

looks a bit shorter than

foreach($this->_records as $key => $value) {
    ${$key} = $value;
}

and native in addition

and var_dump is a great help sometimes (for the next time you run into trouble like this one) :)

Marisolmarissa answered 3/11, 2010 at 14:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.