2010年1月5日 星期二

[PHP]chghtml - 置換html樣板內容

程式用途:置換html設定的樣板文字(以#?及?#包起來的文字)。
範例:
以一個留言版的html模板為例其顯示如下:


#?account?#
#?guestdate?#

#?textguest?#

當你的php讀取完需要置換的資料並儲存成陣列之後。
就可以使用chghtml這個物件來置換網頁資料並做最終輸出。
其使用方式如下:
$data = array("account"=>"使用者帳號","guestdate"=>"發表時間","textguest"=>"文章內容");
require("class.chghtml.php");
$chghtml = new chghtml("樣板檔名");
$chghtml -> chgpage($data);
※置換陣列變數:需要定義key及value,若資料來源為資料庫時,模版的文字名稱需要和
資料庫的欄位名稱相同才能順利置換。若為一般來源,key應該要等於模版文字名稱。

顯示結果:

使用者帳號
發表時間

文章內容

物件檔名:class.chghtml.php
class chghtml{
    
  function __construct($load){
    $this->load = file_get_contents($load);
  }
      
  function chgpage($data = array()){
    $this->chgpage = $this->load;
    foreach($data as $key => $value){
      $value = str_replace("\r\n","<br>",$value);
     $this->chgpage = str_replace("#?".$key."?#",
      html_entity_decode($value),$this->chgpage);
    }
  }
  
  function output(){
   return $this->chgpage;
  }
}

1 則留言: