0

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

4 回答 4

0

大家感谢他们的回复。但是我在我的代码中发现了一个愚蠢的“错误”。在我的模板解析器中,我正在计算模板中的区域并使用 $i 循环遍历它们。然后在一个小部件中,我也必须遍历数据集(导航结构),并再次使用 $i。这造成了我的问题。我只需重命名 $i 即可解决我的问题。

于 2009-12-11T22:01:12.287 回答
0

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

于 2009-12-10T21:38:59.623 回答
0

我喜欢做的一件事是将 obstart() 和 obgetcontents() 包装在 RAII 样式的包装器中。它允许在异常期间进行嵌套和正确处理。实现 __toString() 并且你有一个很好的接口。使用它看起来像这样:


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

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

    return $output;
}

echo someFunction();
?>

当你这样做时,你可以避免担心你是否正确地调用了开始和结束。如果要存储缓冲区输出,则需要在 obendclean() 调用之前立即获取它。

于 2009-12-10T22:05:25.640 回答
0

另一种方法是在 php 执行时将 html 添加到变量中,然后打印该变量,例如:

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

接着

echo $html;

你想要它在哪里。

于 2009-12-10T21:53:53.987 回答