dongsu1951 2014-04-19 01:17 采纳率: 0%
浏览 186
已采纳

为什么ob_get_contents不起作用

I have this code:

<?php
ob_start();
?>
hi
<?php echo ob_get_contents(); ob_end_clean();

But nothing is outputted.
If I remove the ob_end_clean(); the output is hi hi. If ob_flush() isn't called at the end of the app, the contents are automatically flushed, again.

I need to use ob_get_contents() because I am going to implement a simple caching mechanism that saves the the output to a file.

Please help.

Thanks!

  • 写回答

1条回答 默认 最新

  • dongtangxi1584 2014-04-19 01:18
    关注

    Update: I am surprised but your example does actually work with output buffering. I did not think that HTML between php tags would work but it does.

    <?php
    ob_start();
    ?>
    Hello World
    <?php 
    echo "Goodbye";
    $test = ob_get_contents(); ob_end_clean(); echo "output:".$test;
    ?>
    

    This outputs output: Hello World Goodbye.

    The problem is you are echoing ob_get_contents into the buffer. As your question in the comments was about templating, I still think you are going about output buffering wrong. You should push PHP variables into an HTML template, not pull an HTML template into a PHP script. You should also look into a controller/view solution but below is a basic example.

    Templating: For templating, a basic example could be:

    <?php
    ob_start();
    ...PHP LOGIC HERE...
    ...PHP LOGIC HERE...
    ...PHP LOGIC HERE...
    $content = ob_get_contents();
    ob_end_clean();
    ?>
    <html>
    <body>
    <div><?php echo $content; ?></div>
    </body></html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加