Home > Article > Backend Development > Generate a class for a static html file based on a template file_PHP tutorial
Generally, when we use PHP to output an html file, we always use a long string like $head="
The class definition file createhtml.class.php is as follows:
//------------------
//TCreateHTML
//Generate a static html file based on the template file Class
//Author: sharetop
// email:ycshowtop@21cn.com
//-------------------
/ /*****Define the required working functions
//The convention starts with the mark
//Starts with the mark To end
function isbegin($str){
$pattern="";
if(ereg($pattern,$str)) return true;
return false;
}
function isfinish($str){
$pattern="";
if(ereg($pattern,$str)) return true;
return false;
}
function getname($str ){
$tmp=explode("##",$str);
return $tmp[1];
}
//************ ******
//*******Definition class
class TCreateHTML {
var $HTemplate;
var $FileName;
var $ModiString;
//********Interface function
//Construct template
function TCreateHTML($tmplate){
$this->HTemplate=$tmplate;
}
/ /Set the output file name
function SetHTML($filename){
$this->FileName=$filename;
}
//Set the name of the tag and the corresponding replaced string
function EditableBlock($name,$replace){
$this->ModiString[$name]=$replace;
}
//Write HTML file
function WriteHtml(){
$fc=file($this->HTemplate);
$fp=fopen($this->FileName,"w");
$k=count($fc);
$begin =false;
$first=false;
$tag="";
for($i=0;$i<$k;$i++){
if(isbegin($fc[ $i])){
fputs($fp,$fc[$i]);
$begin=true;
$first=true;
$tag=getname($fc[$ i]);
continue;
}
if(isfinish($fc[$i])){
fputs($fp,$fc[$i]);
$begin =false;
$first=false;
$tag="";
continue;
}
if($begin==true){
if($first== true) {
$fc[$i]=$this->ModiString[$tag]." ";
$first=false;
}
else $fc[$i]= "";
}
fputs($fp,$fc[$i]);
}
fclose($fp);
}
//----- ---class end
}
?>
Examples are as follows:
(
First make an html format file and add mark where you want to replace it
Attention! ! This sentence is on a separate line
......
Attention! ! This sentence is on a separate line
etc.
)
require "createhtml.class.php";
$chtml=new TCreateHTML("template.htm");
$chtml->SetHTML("news.htm") ;
$chtml->EditableBlock("aaa","11aa111aa");
$chtml->EditableBlock("bbb","11bbb122bb");
$chtml->EditableBlock(" ccc","11cc333cc");
$chtml->WriteHtml();
?>