国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 php手冊(cè) php生成html文件方法總結(jié)

php生成html文件方法總結(jié)

Apr 18, 2017 am 11:09 AM
php

本文這里匯總了一些自己使用的和網(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
(‘文件名&#39;,&#39;w&#39;); 
fwrite($fp,$temp) or die(‘寫文件錯(cuò)誤&#39;); 
?>

這只是最基本的方法,還不是很實(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&#39;,&#39;w&#39;); 
fwrite($fp,$temp) or die(‘寫文件錯(cuò)誤&#39;); 
//重新導(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=&#39;Content-Type&#39; content=&#39;text/html; charset=gb2312&#39;>";
$html1=$html1."</head>";
$html1=$html1."<body>";
$html1=$html1."<table border=&#39;1&#39; width=&#39;740&#39; cellpadding=&#39;2&#39; cellspacing=&#39;0&#39; bordercolordark=&#39;#f7f7f7&#39; bordercolorlight=&#39;#cccccc&#39;><tr><td align=&#39;center&#39; bgcolor=&#39;#f7f7f7&#39; height=&#39;30&#39;><font size=&#39;3&#39;><b>";
$html1=$html1.$htmltitle;
$html1=$html1."</b></font></td></tr>";
$html1=$html1."<tr><td><font size=&#39;2&#39;>";
$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(&#39;文件寫入成功&#39;);location.href=&#39;111.php&#39;;</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=&#39;$id&#39;";
$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(&#39;模板名稱.tpl&#39;, null, null, false); 
  //下面將內(nèi)容寫入至一個(gè)靜態(tài)文件 
  $fp = fopen(&#39;news.html&#39;, &#39;w&#39;); 
  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)目需求,自由選擇吧

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

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

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

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

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

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

How do I validate user input in PHP to ensure it meets certain criteria? How do I validate user input in PHP to ensure it meets certain criteria? Jun 22, 2025 am 01:00 AM

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

What is data serialization in PHP (serialize(), unserialize())? What is data serialization in PHP (serialize(), unserialize())? Jun 22, 2025 am 01:03 AM

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

How do I embed PHP code in an HTML file? How do I embed PHP code in an HTML file? Jun 22, 2025 am 01:00 AM

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.

What are the best practices for writing clean and maintainable PHP code? What are the best practices for writing clean and maintainable PHP code? Jun 24, 2025 am 12:53 AM

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.

How do I execute SQL queries using PHP? How do I execute SQL queries using PHP? Jun 24, 2025 am 12:54 AM

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

See all articles