Parse PHP code on the fly and store it in a temp var

412 views Asked by At

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?

4

There are 4 answers

0
Ben On BEST ANSWER

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.

1
Glen Solsberry On

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

0
sp. On

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.

0
pestilence669 On

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.