如何使用ob_get_contents()和file_put_contents()创建新文件时保留PHP include()

问题描述:

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

+0

carzy roll-your-own caching,还是别的? – 2014-10-08 01:03:49

您是否有某种页面控制器?如果是,则将所有常用元素放在输出缓冲区外的页面控制器(或控制器中包含的另一个视图)中。如果不是,写一个(或找到一个开源的,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();),或者可以输出两次页面内容。

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

+0

感谢worldofjr,这么多...但是我发现很简单的解决方案,使用这个 '; ?> – floCoder 2014-10-08 01:26:01