首先先建立两个文件夹,一个temp,存储编译前的文件,一个comp,存储编译后的文件,编译前的文件使用{$title}代替<?php echo $title; ?>,然后将前者编译成后者再解析,解析后存储在comp文件夹中
定义一个解析类smarty.class.php
<?php
//定义一个简单的smarty类,来编译html文件
class mini{
public $temp_uri='';//模板文件所在的位置
public $comp_uri='';//模板编译后存放的位置
public $_var=array();//变量数组
public function assign($key,$value){
$this->_var[$key]=$value;
}
public function display($temp){//封装
$uri=$this->complie($temp);
require($uri);
}
/*
String $tempplate模板文件名
return String
*/
public function complie($temp){
//读出模板的内容
$te=$this->temp_uri.'/'.$temp;//编译前的文件
$source=file_get_contents($te);
$comp='./comp/'.$temp.'.php';
//判断这个文件是否是存在
if(file_exists($comp)&&filemtime($comp)>filemtime($te)){//编译后文件存在并且还要这个保存要比编译前的文件保存的早
return $comp;
}
$source=str_replace('{$', '<?php echo $this->_var[\'', $source);
$source=str_replace('}', '\'];?>', $source);
var_dump(file_put_contents($comp,$source));
return $comp;
}
}
?>
在temp目录下的编译前文件01temp.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{$title}</title>
</head>
<body>
下面是php模板的内容<br/>
{$content}
</body>
</html>
控制页面01.php
<?php
require('./smarty.class.php');
$title='商城';
$content='这是我的商城哦';
$smarty=new mini();
$smarty->temp_uri='./temp';
$smarty->comp_uri='./comp';
// $smarty->complie('01temp.html');
$smarty->assign('title',$title);
$smarty->assign('content',$content);
$smarty->display('01temp.html');
?>
运行01.php生成在comp目录下的编译后文件01temp.html.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo $this->_var['title'];?></title>
</head>
<body>
下面是php模板的内容<br/>
<?php echo $this->_var['content'];?>
</body>
</html>
达到正确的结果