2013-09-22 56 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