views:

83

answers:

4

Hello all,

I'm creating my own templatesystem because I only need a few little operations to be supported. One of them is loading widgets with dynamic data generated from a database in my template.

Is there a way to parse PHP code, don't display the result but store it in a variable and then use the generated source from that variable somewhere else?

Right now I'm using ob_get_contents() but whenever I use an echo command it gets overruled and the content displays as the very first thing on my site. This is a behaviour I want to work arround somehow.

Is that possible? Or am i misusing the ob_get_contents completely?

A: 

Make sure you do an ob_start() at the beginning of your page.

gms8994
I have that, I'm calling it multiple times, each time I'm getting a buffer (for the main template and x times for all the widgets) en after each `ob_start`, I'm fetching `ob_get_contents` and then close the buffer.
Ben Fransen
A: 

Another way would be to add html to a variable as your php is executing and then printing that, such as:

$array = array('asd', 'dsa');
$html = '<div id="array">';
foreach ($array as $item) {
    $html .= '<div class="item">'.$item.'</div>';
}
$html .= '</div>';

and then

echo $html;

where you want it to be.

sp
A: 

One thing I like to do is wrap obstart() and obgetcontents() in a RAII style wrapper. It allows for nesting and proper handling during exceptions. Implement __toString() and you have a nice interface. Using it looks something like this:


<?php
function someFunction()
{
    $buffer = new BufferOutput;
    echo 'something';

    $output = (string)$buffer;
    unset($buffer); // for illustration. automatically calls ob_end_clean()

    return $output;
}

echo someFunction();
?>

When you do it this way, you can avoid worrying about whether you called start & end properly. If you're going to store the buffer output, you'll need to grab it right away before your obendclean() call.

Pestilence
A: 

Everybody thanks for their replies. But i found a silly 'bug' in my code. In my templateparser I'm counting the regions in a template and loop through them, using $i. Then in a widget I had to iterate through a dataset (navigation structure) too, and used $i again. This was creating my problem. I simply had to rename $i to solve my problem.

Ben Fransen