动态解析 PHP 代码并将其存储在临时变量中
我正在创建自己的模板系统,因为我只需要支持一些小操作。其中之一是加载带有从我的模板中的数据库生成的动态数据的小部件。
有没有一种方法可以解析 PHP 代码,不显示结果,而是将其存储在变量中,然后在其他地方使用该变量生成的源代码?
现在我正在使用 ob_get_contents() ,但每当我使用 echo 命令时,它都会被否决,并且内容会显示为我网站上的第一件事。这是我想以某种方式解决的行为。
这可能吗?或者我完全滥用了ob_get_contents?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
确保在页面开头执行
ob_start()
。Make sure you do an
ob_start()
at the beginning of your page.另一种方法是在 php 执行时将 html 添加到变量中,然后打印它,例如:
然后打印到
您想要的位置。
Another way would be to add html to a variable as your php is executing and then printing that, such as:
and then
where you want it to be.
我喜欢做的一件事是将 obstart() 和 obgetcontents() 包装在 RAII 风格的包装器中。它允许在异常期间进行嵌套和正确处理。实现 __toString() 并且你有一个漂亮的界面。使用它看起来像这样:
当你这样做时,你可以避免担心你是否调用了 start & 。正确结束。如果要存储缓冲区输出,则需要在调用 obendclean() 之前立即获取它。
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:
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.
大家感谢他们的回复。但我在我的代码中发现了一个愚蠢的“错误”。在我的模板解析器中,我正在计算模板中的区域并使用 $i 循环遍历它们。然后在一个小部件中,我也必须迭代数据集(导航结构),并再次使用 $i。这造成了我的问题。我只需重命名 $i 即可解决我的问题。
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.