【问题标题】:How to preserve PHP include() while creating new file with ob_get_contents() and file_put_contents()如何在使用 ob_get_contents() 和 file_put_contents() 创建新文件时保留 PHP include()
【发布时间】:2014-10-08 00:56:46
【问题描述】:

我想使用 ob_start() 和 ob_get_contents() 创建包含动态内容的新文件,以抓取整个创建的页面。然后我使用 file_put_contents() 来创建包含生成内容的页面。但是,问题在于,它解析 PHP include() 并仅存储 HTML 内容。有什么方法可以保留 PHP include(),这样如果我们想要小更新就不必更改每个文件代码?

【问题讨论】:

  • carzy roll-your-own缓存,还是别的什么?

标签: php include ob-start


【解决方案1】:

你有某种页面控制器吗?如果是,则将该页面控制器(或控制器中包含的另一个视图)中的所有公共元素放在输出缓冲区之外。如果没有,写一个(或找一个开源的,like this)。

例如;

// Page controller
include 'path/to/Page.class.php';
$page->contentfile = getpage(); // get the filename of the page using the url string
$page->header = "..."; // header string
$page->footer = "..."; // footer string
ob_start();
include_once($page->contentfile);
$content = ob_get_contents();
ob_end_clean();

echo $pageobj->display($content);

在 page.php 中,您可以使用 $page->title = ''; 之类的方式设置标题等,这些设置将被记住在页面控制器中。

请记住,您需要在文件结束之前清理输出缓冲区(ob_end_clean();),否则页面内容可能会输出两次。

上面的代码只是一个示例,但它应该为您指明正确的方向。

【讨论】:

  • 感谢 worldofjr,为此非常感谢......但是我发现使用这个 '; ?>
猜你喜欢
  • 1970-01-01
  • 2015-04-01
  • 1970-01-01
  • 2014-11-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
相关资源
最近更新 更多