"
%>
<%
Response. Write ("successful
GenerateFile :")
Response. Write ("
")
Response. Write Html_Temp
%>
PHPGenerateStaticWebpage Method
I saw a lot of friends posting in various places asking PHPGenerateStaticThe system method of the article has previously been used in such a system. I would like to discuss some ideas for your reference. Now let's review some basic concepts.
I. PHP scripts and dynamic pages.
A PHP script is a server-side scripting program that can be mixed with HTML files by embedding methods, classes, function encapsulation, and other forms to process user requests in a template. Regardless of the method, the basic principle is as follows. Requests made by the client, request a page -----> the WEB server introduces the specified script for processing -----> the script is loaded to the server -----> the PHP parser specified by the server parses the script to form an HTML language ----> the parsed HTML statement is returned to the browser as a package. It is not hard to see that after the page is sent to the browser, PHP does not exist and has been converted into HTML statements. The customer requests a dynamic file, in fact there is no real file, it is a PHP parsing to form a corresponding page, and then sent back to the browser. This page processing method is called "dynamic page ".
II,StaticPage.
StaticA page is a page on the server that only contains HTML, JS, CSS, and other clients to run scripts. The processing method is. The client sends a request to a page ----> the WEB server confirms and loads a page ----> the WEB server sends the page back to the browser as a package. From this process, we can compare the dynamic page to see it now. Dynamic Pages must be parsed by the PHP parser of the WEB server. Generally, you need to connect to the database for database access before forming an HTML language information package.StaticPage, no need to parse, no need to connect to the database, direct transmission, can greatly reduce the pressure on the server, improve server load capabilities, greatly provide page opening speed and overall website opening speed. However, the disadvantage is that the request cannot be processed dynamically and the file must exist on the server.
3. parsing templates and templates.
The template does not fill in the html file. For example:
Temp.html
{Title}
This is a {file} file's templets
PHP processing:
Templetest. php
$ Title = "http://siyizhu.com test template ";
$ File = "TwoMax Inter test templet,
Author: Matrix @ Two_Max ";
$ Fp = fopen ("temp.html", "r ");
$ Content = fread ($ fp, filesize ("temp.html "));
$ Content. = str_replace ("{file}", $ file, $ content );
$ Content. = str_replace ("{title}", $ title, $ content );
Echo $ content;
?>
Template parsing process: The result filling (content) obtained after parsing and processing by the PHP script is entered into the processing process of the template. The template class is usually used. Currently, popular template parsing classes include phplib, smarty, fastsmarty, and so on. The principle of template Parsing is usually replaced. Some programmers are also used to putting judgment, loop, and other processing into the template file, using parsing class processing. A typical application is the block concept, which is simply a loop processing. The PHP script specifies the number of loops, how to cyclically substitute, and so on, and then the template parsing class specifically implements these operations.
Okay, comparedStaticThe advantages and disadvantages of pages and dynamic pages. Now let's talk about how to use PHPGenerateStaticFile.
PHPGenerateStaticPages do not refer to PHP dynamic parsing, HTML pages output, but HTML pages created with PHP. At the same time, because of the non-writability of HTML, if the HTML we create is modified, We need to delete it and try again.GenerateYou can. (You can also modify the regular expression, but I personally think it is better to delete it and try again.GenerateIt is quick, and some are not worth the candle .)
Let's get down to the truth. Php fans who have used PHP file operation functions know that there is a file operation function fopen in PHP, that is, open the file. If the file does not exist, try to create it. This is the theoretical basis for PHP to Create HTML files. As long as the folder used to store HTML files has the write permission (that is, permission definition 0777), you can create the file. (For UNIX systems, Windows systems do not need to be considered .) For example, if we modify the last sentence and specifyGenerateTest.htmlStaticFile:
$ Title = "http://siyizhu.com test template ";
$ File = "TwoMax Inter test templet,
Author: Matrix @ Two_Max ";
$ Fp = fopen ("temp.html", "r ");
$ Content = fread ($ fp, filesize ("temp.html "));
$ Content. = str_replace ("{file}", $ file, $ content );
$ Content. = str_replace ("{title}", $ title, $ content );
// Echo $ content;
$ Filename = "test/test.html ";
$ Handle = fopen ($ filename, "w"); // open the file pointer and create a file
/*
Check whether the file is created and writable.
*/
If (! Is_writable ($ filename )){
Die ("file:". $ filename. "cannot be written. Check its attributes and try again! ");
}
If (! Fwrite ($ handle, $ content) {// write information to the file
Die ("GenerateFile ". $ filename." failed! ");
}
Fclose ($ handle); // close the pointer
Die ("creating File". $ filename. "successful! ");
?>
For solutions to common problems in practical applications, refer:
I. List of articles:
Create a field in the database, record the file name, eachGenerateOne file will automaticallyGenerateFor recommended articles, you only need to point toStaticThe page in the specified folder of the file. Use PHP to process the article list and save it as a string,GenerateYou can replace this string on the page. For example, add the mark {articletable} to the table where the article list is placed on the page, and process the file in PHP:
$ Title = "http://siyizhu.com test template ";
$ File = "TwoMax Inter test templet,
Author: Matrix @ Two_Max ";
$ Fp = fopen ("temp.html", "r ");
$ Content = fread ($ fp, filesize ("temp.html "));
$ Content. = str_replace ("{file}", $ file, $ content );
$ Content. = str_replace ("{title}", $ title, $ content );
//GenerateStart List
$ List = '';
$ SQL = "select id, title, filename from article ";
$ Query = mysql_query ($ SQL );
While ($ result = mysql_fetch_array ($ query )){
$ List. = ''. $ result ['title'].'
';
}
$ Content. = str_replace ("{articletable}", $ list, $ content );
//GenerateList ended
// Echo $ content;
$ Filename = "test/test.html ";
$ Handle = fopen ($ filename, "w"); // open the file pointer and create a file
/*
Check whether the file is created and writable.
*/
If (! Is_writable ($ filename )){
Die ("file:". $ filename. "cannot be written. Check its attributes and try again! ");
}
If (! Fwrite ($ handle, $ content) {// write information to the file
Die ("GenerateFile ". $ filename." failed! ");
}
Fclose ($ handle); // close the pointer
Die ("creating File". $ filename. "successful! ");
?>
Ii. Paging problems.
For example, we specify 20 pages per page. If the number of articles in a subchannel list is 45 in the database, we first obtain the following parameters through the query: 1, the total number of pages; 2, the number of entries per page. Step 2: for ($ I = 0; $ I <allpages; $ I ++), page Element Acquisition, analysis, and articleGenerateIn this loop. The difference is that die ("Create File". $ filename. "succeeded! "; This sentence is removed and displayed after the loop, because the statement will stop the program execution. Example:
$ Fp = fopen ("temp.html", "r ");
$ Content = fread ($ fp, filesize ("temp.html "));
$ Onepage = '20 ';
$ SQL = "select id from article where channel = '$ channelid '";
$ Query = mysql_query ($ SQL );
$ Num = mysql_num_rows ($ query );
$ Allpages = ceil ($ num/$ onepage );
For ($ I = 0; $ I <$ allpages; $ I ++ ){
If ($ I = 0 ){
$ Indexpath = "index.html ";
} Else {
$ Indexpath = "index _". $ I. "html ";
}
$ Start = $ I * $ onepage;
$ List = '';
$ SQL _for_page = "select name, filename, title from article where channel = '$ channelid' limit $ start, $ onepage ";
$ Query_for_page = mysql_query ($ SQL _for_page );
While ($ result = $ query_for_page ){
$ List. = ''. $ title .'
';
}
$ Content = str_replace ("{articletable}", $ list, $ content );
If (is_file ($ indexpath )){
@ Unlink ($ indexpath); // delete a file if it already exists
}
$ Handle = fopen ($ indexpath, "w"); // open the file pointer and create a file
/*
Check whether the file is created and writable.
*/
If (! Is_writable ($ indexpath )){
Echo "file:". $ indexpath. "cannot be written. Check its attributes and try again! "; // Modify it to echo
}
If (! Fwrite ($ handle, $ content) {// write information to the file
Echo"GenerateFile ". $ indexpath." failed! "; // Modify it to echo
}
Fclose ($ handle); // close the pointer
}
Fclose ($ fp );
Die ("GenerateThe paging file is completed, as shown in figureGenerateIncomplete. Check the File Permission System and try again.Generate! ");
?>
This is a general idea, such as other data.Generate, Data input and output check, paging content pointing, etc. can be added to the page as appropriate.
In the actual article system processing process, there are still many issues to consider. Different from dynamic pages, there are still many things to note. However, the general idea is that, in other aspects, the opposite is true.
ASP. NETGenerateStaticWebpage Method
Environment: Microsoft. NET Framework SDK v1.1
OS: Windows Server 2003 Chinese Version
ASP. NetGenerateStaticHTML page
Implemented in AspGenerateStaticThe FileSystemObject object used on the page!
System. IO is involved in. Net.
The following is the program code Note: This code is not original! Reference others' code
//GenerateHTML page
Public static bool WriteFile (string strText, string strContent, string strAuthor)
{
String path = HttpContext. Current. Server. MapPath ("/news /");
Encoding code = Encoding. GetEncoding ("gb2312 ");
// Read the Template File
String temp = HttpContext. Current. Server. MapPath ("/news/text.html ");
StreamReader sr = null;
StreamWriter sw = null;
String str = "";
Try
{
Sr = new StreamReader (temp, code );
Str = sr. ReadToEnd (); // read the file
}
Catch (Exception exp)
{
HttpContext. Current. Response. Write (exp. Message );
HttpContext. Current. Response. End ();
Sr. Close ();
}
String htmlfilename = DateTime. Now. ToString ("yyyyMMddHHmmss") + ". html ";
// Replace content
// At this time, the template file has been read into the variable named str
Str = str. Replace ("ShowArticle", strText); // ShowArticle on the template page
Str = str. Replace ("biaoti", strText );
Str = str. Replace ("content", strContent );
Str = str. Replace ("author", strAuthor );
// Write an object
Try
{
Sw = new StreamWriter (path + htmlfilename, false, code );
Sw. Write (str );
Sw. Flush ();
}
Catch (Exception ex)
{
HttpContext. Current. Response. Write (ex. Message );
HttpContext. Current. Response. End ();
}
Finally
{
Sw. Close ();
}
Return true;
This function is stored in the Conn. CS base class.
Reference in the Code for adding news: Project name: Hover
If (Hover. Conn. WriteFilethis. Title. Text. ToString), this. Content. Text. ToString), this. Author. Text. ToString )))
{
Response. Write ("added successfully ");
}
Else
{
Response. Write ("GenerateHTML error! ");
}
Template page text.html code
ShowArticle
Biaoti
Content
Author
Biaoti
Content
Author
A prompt is displayed, indicating that an html file with the current time as the file name is displayed! The above only writes the passed parameters directly to the HTML file. In actual applications, you need to add the database before writing the HTML file.