本文這里匯總了一些自己使用的和網(wǎng)上搜集來的php生成html靜態(tài)文件的方法,非常的使用,也分析了他們的優(yōu)缺點(diǎn),是篇非常不錯(cuò)的文章,這里推薦給大家。
我經(jīng)常會(huì)在網(wǎng)上看到有人問怎么將整個(gè)動(dòng)態(tài)的網(wǎng)站靜態(tài)化,其實(shí)實(shí)現(xiàn)的方法很簡(jiǎn)單。
?代碼如下:
<?php //在你的開始處加入 ob_start(); ob_start(); //以下是你的代碼 //在結(jié)尾加入 ob_end_clean(),并把本頁(yè)輸出到一個(gè)變量中 $temp = ob_get_contents(); ob_end_clean(); //寫入文件 $fp = fopen (‘文件名','w'); fwrite($fp,$temp) or die(‘寫文件錯(cuò)誤'); ?>
這只是最基本的方法,還不是很實(shí)用,因?yàn)榫W(wǎng)站是要更新的,要定期重新生成HTML
下面是我用的方法:
代碼如下:
if(file_exists(“xxx.html”)) { $time = time(); //文件修改時(shí)間和現(xiàn)在時(shí)間相差半小時(shí)一下的話,直接導(dǎo)向html文件,否則重新生成html if($time - filemtime(“xxx.html”) < 30*60) { header(“Location:xxx.html”); } } //在你的開始處加入 ob_start(); ob_start(); //頁(yè)面的詳細(xì)內(nèi)容 //在結(jié)尾加入 ob_end_clean(),并把本頁(yè)輸出到一個(gè)變量中 $temp = ob_get_contents(); ob_end_clean(); //寫入文件 $fp = fopen(‘xxx.html','w'); fwrite($fp,$temp) or die(‘寫文件錯(cuò)誤'); //重新導(dǎo)向 header(“Location:xxx.html”);
上面用的緩存文件在大量生成時(shí)會(huì)出現(xiàn)負(fù)載過重,下面我們介紹一種更為高效的方法
以下是輸入內(nèi)容的提交頁(yè)面:
文件名:aa.html
代碼如下:
<html> <head> <title>提交頁(yè)面</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </head> <body> <form method="post" action="bb.php"> 標(biāo)題:<input type="text" name="htmltitle"><br> 內(nèi)容:<textarea rows="8" cols="45" name="htmlbody"></textarea><br> <input type="submit" name="submit" value="添加新聞"> </form> </body> </html>
以下是代碼片段:
文件名:bb.php
代碼如下:
<?php //定義日期函數(shù) function getdatetime() { $datetime=getdate(); $strReturn=$datetime["year"]."-"; $strReturn=$strReturn.$datetime["mon"]."-"; $strReturn=$strReturn.$datetime["mday"]; return $strReturn; } //定義時(shí)間函數(shù)(文件名) function gettime() { $times=getdate(); $strtime=$times["year"]; $strtime=$strtime.$times["mon"]; $strtime=$strtime.$times["mday"]; $strtime=$strtime.$times["minutes"]; $strtime=$strtime.$times["seconds"]; return $strtime; } ?>
<?php //判斷提交值是否為空 $submit=$_POST["submit"]; //定義文件頭部信息 $htmltitle=$_POST["htmltitle"]; //定義文件內(nèi)容 $htmlbody=$_POST["htmlbody"]; if ($submit) { //定義html文件標(biāo)簽 $html1=$html1."<html>"; $html1=$html1."<head>"; $html1=$html1."<title>"; $html1=$html1.$htmltitle; $html1=$html1."</title>"; $html1=$html1."<meta http-equiv='Content-Type' content='text/html; charset=gb2312'>"; $html1=$html1."</head>"; $html1=$html1."<body>"; $html1=$html1."<table border='1' width='740' cellpadding='2' cellspacing='0' bordercolordark='#f7f7f7' bordercolorlight='#cccccc'><tr><td align='center' bgcolor='#f7f7f7' height='30'><font size='3'><b>"; $html1=$html1.$htmltitle; $html1=$html1."</b></font></td></tr>"; $html1=$html1."<tr><td><font size='2'>"; $html1=$html1.$htmlbody; $html1=$html1."</font></td></tr></table>"; $html1=$html1."</body>"; $html1=$html1."</html>"; //判斷今天的文件夾是否存在 if (!is_dir(getdatetime())) { //如果不存在就建立 mkdir(getdatetime(),0777); } //寫成html文件 $filedir=getdatetime(); $filename=gettime(); $filename=$filename.".html"; $fp=fopen("$filedir/$filename","w"); fwrite($fp,$html1); fclose ($fp); echo "<script>alert('文件寫入成功');location.href='111.php';</script>"; } ?>
如果提示文件寫入成功,那你就成功了,然后回到你的相應(yīng)目錄里看看有沒有生成靜態(tài)的html文件!
smarty模板生成方法
代碼如下:
<?php require_once("./config/config.php"); ob_start(); $id=$_GET[id]; $sql="select * from table_name where id='$id'"; $result= mysql_query ($sql); $rs=mysql_fetch_object($result); $smarty->assign("showtitle",$rs->title); $smarty->assign("showcontent",$rs->content); $smarty-> display ("content.html"); $this_my_f= ob_get_contents(); ob_end_clean(); $filename = "$id.html"; tohtmlfile_cjjer($filename,$this_my_f); // 文件生成函數(shù) function tohtmlfile_cjjer($file_cjjer_name,$file_cjjer_content){ if (is_file ($file_cjjer_name)){ @unlink ($file_cjjer_name); //存在,就刪除 } $cjjer_handle = fopen ($file_cjjer_name,"w"); //創(chuàng)建文件 if (!is_writable ($file_cjjer_name)){ //判斷寫權(quán)限 return false; } if (!fwrite ($cjjer_handle,$file_cjjer_content)){ return false; } fclose ($cjjer_handle); //關(guān)閉指針 return $file_cjjer_name; //返回文件名 } ?>
smarty中有一個(gè)獲取模板頁(yè)內(nèi)容方法fetch(), 它的聲明原形是這樣的:
代碼如下:
<?php $smarty = new Smarty(); //其它模板替換語(yǔ)法... //下面這句取得頁(yè)面中所有內(nèi)容, 注意最后一個(gè)參數(shù)為false $content = $smarty->fetch('模板名稱.tpl', null, null, false); //下面將內(nèi)容寫入至一個(gè)靜態(tài)文件 $fp = fopen('news.html', 'w'); fwrite($fp, $content); fclose($fp); //OK, 到這里這個(gè)news.html靜態(tài)頁(yè)就生成了, 你可以處理你下一步的工作了 ?>
好了結(jié)合上面的方法我們生成文件幾乎原理都一樣,先把數(shù)據(jù)讀取出來然后給我們定義好的模板,最后利用fopen函數(shù)生成一個(gè).html的文件
以上幾種php生成html靜態(tài)文件的方法原理上都大同小異,只是在方法上略有不同,都有優(yōu)缺點(diǎn),大家根據(jù)自己的項(xiàng)目需求,自由選擇吧

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas
