2013-09-22 57 views
0

我试图让我的生活变得更容易,并使所有页面从一个文件具有相同的页脚和头部内容,这是我迄今为止:添加大量的html和php内容作为PHP变量

页的内容

<?php 
include ("content.php"); 

echo $page_header; 

?> 

<div id="content"> 
</div> 

<?php 

echo $page_footer; 

?> 

content.php

<?php 

    // This is the header which we want to have on all pages 
    $page_header = include ("resources/content/header.php"); 

    // This is the footer which we want on all pages 
    $page_footer = include ("resources/content/footer.php"); 

?> 

的header.php例

<html> 
    <head> 
     <title>This is my title</title> 
    </head> 
    <body> 
     <div id="logo"> 
     </div> 

Footer.php例

 <div id="footer">Copyright to me!</div> 
    </body> 
</html> 

的我有问题是我的header.php内容是不是所有与页面格式显示,并导致问题。 header.php确实包含了一些php if声明和一些内嵌的javascript ...应该这样吗?

有没有更好的方法呢?

请注意:我使用本地PHP 5,我的服务器是PHP 4所以答案需要两个

+1

'include(“resources/content/footer.php”);'而不是将它分配给一个变量 –

+0

真的没有什么真正的错误,你有没有尝试验证你的HTML?有没有任何理由一些有条件的PHP或内联JS应该有所作为,你可以发布header.php内容 – dougajmcdonald

+0

我写了类似的问题[这里](http://stackoverflow.com/questions/18937026/insert -page功能于HTML设计/ 18937678#18937678)。 – mdesdev

回答

2

一种工作方式是使用输出缓冲功能这一点。

变化content.php文件:

ob_start(); 
include ("resources/content/header.php"); 
$page_header = ob_get_clean(); 

ob_start(); 
include ("resources/content/footer.php"); 
$page_footer = ob_get_clean(); 

ob_start()功能的任何输出创建一个临时缓冲区,然后include()使得它的输出不是页面响应,但已通过ob_start()创建的缓冲区。 ob_get_clean()收集缓冲区的内容,破坏它并将收集的数据作为字符串返回。


如提及@u_mulder另一种方法是简单地include()这些文件的权利,他们需要的地方。

变化页面内容文件:

<?php include ("resources/content/header.php"); ?> 

<div id="content"> 
</div> 

<?php include ("resources/content/footer.php"); ?> 

然而,在某些时候你可能需要一些复杂的模板处理引擎。有很多PHP的。

+0

这工作得很好!请你可以详细了解使用'ob_start();'over'include();'的好处吗? – AaronHatton

+0

@AaronHatton注意更新。没有好处。它只是防止直接输出,并允许收集和预处理它,然后作为对客户端浏览器的响应。 – BlitZ