php產生html簡單代碼執行個體

來源:互聯網
上載者:User

執行個體一

原理剖析:

當我們製作資料量大以及訪問人數多的網站時往往會採用動態產生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頁<?phpob_start();   //開啟伺服器緩衝include_once '../gsjj.php'; $ctx=ob_get_contents();     //擷取緩衝ob_end_clean();     //清空緩衝 $fh=fopen("../gsjj.html","w+");  fwrite($fh,$ctx);    //寫入html,產生htmlfclose($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.lengthPagesLen=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)+1var 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的類

<?phpclass 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);                }            }        }        }?>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.