您的位置:首页 > Web前端 > HTML

php生成html简单代码实例

2012-04-28 16:46 851 查看
实例一

原理剖析:

当我们制作数据量大以及访问人数多的网站时往往会采用动态生成html静态页面的方法,这样做的好处是用户直接访问静态页面,减轻了服务器的负担,又可以对搜索引擎更加友好,可谓一举两得;

其原理是先读入模板文件,然后按照一定的规则替换模板中的标签,具体实现如下:

index.tpl 模板文件代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{title}</title>
</head>
<body>
{content}
</body>
</html>


index.php 服务端代码:

<?php
$data = array('id' => 1, 'title' => '这里是标题', 'content' => '这里是内容');
$tpl = 'index.tpl';
$content = file_get_contents($tpl);     //读取模板文件的内容
$content = str_replace('{title}',$data['title'],$content);  //用具体数据来替换模板标签
$content = str_replace('{content}',$data['content'],$content);
file_put_contents($data['id'].'.html',$content);   //将替换后的内容写进html文件中
?>


这里是从数组中直接读取数据,实际过程中可以将数据库读取的数据保存在数组中,然后用循环的方法实现替换就行了。

实例二

//单页生成html页
<?php
ob_start();   //开启服务器缓存
include_once '../gsjj.php';
$ctx=ob_get_contents();     //获取缓存
ob_end_clean();     //清空缓存
$fh=fopen("../gsjj.html","w+");
fwrite($fh,$ctx);    //写入html,生成html
fclose($fh);
echo "<script>alert('文件生成成功');location.href='makehtml.php';</script>";
?>

//新闻列表带分页生成html页
<?php
$fp = fopen ("../new.html","r");  //只读方式打开 new.html模板,将文件指针指向文件头
$content = fread ($fp,filesize ("../new.html"));    //读取整个文件内容
$list = '';
$num=0;
$sql= "select * from news ";
$result=mysql_query($sql);
while($row=mysql_fetch_assoc($result))
{    //查询entries表,取出列表项
$num++;
if($row["url"]=="")
{
$list .= "<ul class='news' id='ul'><li><a href='".$row["tid"].".html'>".$row['title']."</a></li></ul>";
}
else
{
$list .= "<ul class='news' id='ul'><li><a href='".$row["url"]."' target='_blank'>".$row['title']."</a></li></ul>";
}
}
$content= str_replace ("{articletable}",$list,$content);
//生成列表结束
// echo $content;
$filename = "../news.html";
$filename1 = "../new.html";
$handle = fopen ($filename,"w"); //打开文件指针,创建文件
/*
 检查文件是否被创建且可写
*/
if (!is_writable ($filename)){
die ("文件:".$filename."不可写,请检查其属性后重试!");
}
if (!fwrite ($handle,$content)){ //将信息写入文件
die ("生成文件".$filename."失败!");
}
fclose ($handle); //关闭指针
die ("Create file ".$filename." success !");
?>


模板页面 new.html
<div id="mydiv">
{articletable}
</div>
<div id="changpage" style="text-align:center; color:#333333; margin-top:50px"></div>
<script>
var obj,j;
var page=0;
var nowPage=0;//当前页
var listNum=40;//每页显示<ul>数
var PagesLen;//总页数
var PageNum=500;//分页链接接数(5个)
onload=function(){
obj=document.getElementById("mydiv").getElementsByTagName("ul");
j=obj.length
PagesLen=Math.ceil(j/listNum);
upPage(0)
}
function upPage(p){
nowPage=p
//内容变换
for (var i=0;i<j;i++){
obj[i].style.display="none"
}
for (var i=p*listNum;i<(p+1)*listNum;i++){
if(obj[i])obj[i].style.display="block"
}
//分页链接变换
strS='<a href="###" onclick="upPage(0)" style="color:#000000">首页</a> '
var PageNum_2=PageNum%2==0?Math.ceil(PageNum/2)+1:Math.ceil(PageNum/2)
var PageNum_3=PageNum%2==0?Math.ceil(PageNum/2):Math.ceil(PageNum/2)+1
var strC="",startPage,endPage;
if (PageNum>=PagesLen) {startPage=0;endPage=PagesLen-1}
else if (nowPage<PageNum_2){startPage=0;endPage=PagesLen-1>PageNum?PageNum:PagesLen-1}//首页
else {startPage=nowPage+PageNum_3>=PagesLen?PagesLen-PageNum-1: nowPage-PageNum_2+1;var t=startPage+PageNum;endPage=t>PagesLen?PagesLen-1:t}
for (var i=startPage;i<=endPage;i++){
if (i==nowPage)strC+='<a href="###" style="color:red;font-weight:700;" onclick="upPage('+i+')">'+(i+1)+'</a> '
else strC+='<a href="###" onclick="upPage('+i+')">'+(i+1)+'</a> '
}
strE=' <a href="###" onclick="upPage('+(PagesLen-1)+')" style="color:#000000">尾页</a> '
strE2=nowPage+1+"/"+PagesLen+"页"+" 共"+j+"条"
document.getElementById("changpage").innerHTML=strS+strC+strE+strE2
}
</script>
</div>


//后台添加文章生成 html
<?php
mt_srand((double)microtime()*1000000);
$randval = mt_rand(1, 99999);
$tmp_num = $randval;
$title=$_POST['title'];
$gjc=$_POST['gjc'];
$content=trim($_POST['content']);
$bz=$_POST['bz'];
$url=$_POST['url'];
$shijian=date("Y-m-d");
$mobanpath=$root."../newxinxi.html";
$fp=fopen($mobanpath,"rb");
$news_contents=fread($fp,filesize($mobanpath));
$news_contents=str_replace("{-news_title-}",$title,$news_contents);
$news_contents=str_replace("{-news_gjc-}",$gjc,$news_contents);
$news_contents=trim(str_replace("{-content-}",$content,$news_contents));
$news_contents=str_replace("{-bz-}",$bz,$news_contents);
$news_contents=str_replace("{-shijian-}",$shijian,$news_contents);
$news_contents=str_replace("{-url-}",$url,$news_contents);
$news_contents=str_replace("{-shijian-}",$shijian,$news_contents);
$list = '';
$num=1;
$sql= "select * from news order by id desc limit 0,1";
$result=mysql_query($sql);
while($row=mysql_fetch_assoc($result))
{//查询entries表,取出列表项
/*$num=$nmu+1;	*/
$id=$row["id"]+1;

$filename="".$tmp_num.".html";

}
$num++;
$newspath=$root."../".$filename;
$fp1=fopen($newspath,"w");
fwrite($fp1,$news_contents,strlen($news_contents));

$sql="insert into news (title,shijian,content,gjc,bz,url,tid) values ('$_POST[title]','$shijian','$_POST[content]','$_POST[gjc]','$_POST[bz]','$_POST[url]','$tmp_num')";
$result=mysql_query($sql);
echo "<script>";
echo "alert('新闻添加成功!');";
echo "window.location=('news.php');";
echo "</script>";
?>


其他——php生成html的类



<?php
class html
{
var $dir; //dir for the htmls(without/)
var $rootdir; //root of html files(without/):html
var $name; //html文件存放路径
var $dirname; //指定的文件夹名称
var $url; //获取html文件信息的来源网页地址
var $time; //html文件信息填加时的时间
var $dirtype; //目录存放方式:year,month,,,,
var $nametype; //html文件命名方式:name

function html($nametype = 'name', $dirtype = 'year', $rootdir = 'html')
{
$this -> setvar($nametype, $dirtype, $rootdir);
}

function setvar($nametype = 'name', $dirtype = 'year', $rootdir = 'html')
{
$this -> rootdir = $rootdir;
$this -> dirtype = $dirtype;
$this -> nametype = $nametype;
}

function createdir($dir = '')
{
$this -> dir = $dir?$dir:$this -> dir;

if (!is_dir($this -> dir))
{
$temp = explode('/', $this -> dir);
$cur_dir = '';
for($i = 0;$i < count($temp);$i++)
{
$cur_dir .= $temp[$i] . '/';
if (!is_dir($cur_dir))
{
@mkdir($cur_dir, 0777);
}
}
}
}

function getdir($dirname = '', $time = 0)
{
$this -> time = $time?$time:$this -> time;
$this -> dirname = $dirname?$dirname:$this -> dirname;

switch($this -> dirtype)
{
case 'name':
if(empty($this -> dirname))
$this -> dir = $this -> rootdir;
else
$this -> dir = $this -> rootdir . '/' . $this -> dirname;
break;
case 'year':
$this -> dir = $this -> rootdir . '/' . date("Y", $this -> time);
break;

case 'month':
$this -> dir = $this -> rootdir . '/' . date("Y-m", $this -> time);
break;

case 'day':
$this -> dir = $this -> rootdir . '/' . date("Y-m-d", $this -> time);
break;
}

$this -> createdir();

return $this -> dir;
}

function geturlname($url = '')
{
$this -> url = $url?$url:$this -> url;

$filename = basename($this -> url);
$filename = explode(".", $filename);
return $filename[0];
}

function geturlquery($url = '')
{
$this -> url = $url?$url:$this -> url;

$durl = parse_url($this -> url);
$durl = explode("&", $durl[query]);
foreach($durl as $surl)
{
$gurl = explode("=", $surl);
$eurl[] = $gurl[1];
}
return join("_", $eurl);
}

function getname($url = '', $time = 0, $dirname = '')
{
$this -> url = $url?$url:$this -> url;
$this -> dirname = $dirname?$dirname:$this -> dirname;
$this -> time = $time?$time:$this -> time;

$this -> getdir();

switch($this -> nametype)
{
case 'name':
$filename = $this -> geturlname() . '.htm';
$this -> name = $this -> dir . '/' . $filename;
break;

case 'time':
$this -> name = $this -> dir . '/' . $this -> time . '.htm';
break;

case 'query':
$this -> name = $this -> dir . '/' . $this -> geturlquery() . '.htm';
break;

case 'namequery':
$this -> name = $this -> dir . '/' . $this -> geturlname() . '-' . $this -> geturlquery() . '.htm';
break;

case 'nametime':
$this -> name = $this -> dir . '/' . $this -> geturlname() . '-' . $this -> time . '.htm';
break;

}
return $this -> name;
}

function createhtml($url = '', $time = 0, $dirname = '', $htmlname = '')
{
$this -> url = $url?$url:$this -> url;
$this -> dirname = $dirname?$dirname:$this -> dirname;
$this -> time = $time?$time:$this -> time;
// 上面保证不重复地把变量赋予该类成员
if(empty($htmlname))
$this -> getname();
else
$this -> name = $dirname . '/' . $htmlname; //得到name

$content = file($this -> url) or die("Failed to open the url " . $this -> url . " !");;

// /////////////关键步---用file读取$this->url

$content = join("", $content);
$fp = @fopen($this -> name, "w") or die("Failed to open the file " . $this -> name . " !");
if(@fwrite($fp, $content))
return true;
else
return false;
fclose($fp);
}
// ///////////////以name为名字生成html
function deletehtml($url = '', $time = 0, $dirname = '')
{
$this -> url = $url?$url:$this -> url;
$this -> time = $time?$time:$this -> time;

$this -> getname();

if(@unlink($this -> name))
return true;
else
return false;
}

/**
* function::deletedir()
* 删除目录
*
* @param $file 目录名(不带/)
* @return
*/
function deletedir($file)
{
if(file_exists($file))
{
if(is_dir($file))
{
$handle = opendir($file);
while(false !== ($filename = readdir($handle)))
{
if($filename != "." && $filename != "..")
$this -> deletedir($file . "/" . $filename);
}
closedir($handle);
rmdir($file);
return true;
}else{
unlink($file);
}
}
}

}
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: