Parse PHP code on the fly and store it in a temp var
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 w开发者_如何学Pythonork arround somehow.
Is that possible? Or am i misusing the ob_get_contents
completely?
Make sure you do an ob_start()
at the beginning of your page.
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.
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.
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.
精彩评论