Generate static pages [Asp/PHP/aspx]

Source: Internet
Author: User
Tags fread
ASP method for generating static Web pages
With the increase of Website access traffic, every read from the database is at the cost of efficiency. Many users who use access as the database will have a deep understanding. When using static pages for search, they will also be given priority. The popular practice on the Internet is to write the source code of the data into the database and then read it from the database to generate a static surface, which increases the size of the database. Generating static pages from existing ASP pages will save a lot.

In the following example, index. asp? Id = 1/index. asp? Id = 2/index. asp? Id = 3/these three dynamic pages do not generate ndex1.htm,index2.htm,index3.htm exists in the root directory:

<%
Dim strurl, item_classid, ID, filename, filepath, do_url, html_temp
Html_temp = "<ul>"
For I = 1 to 3
Html_temp = html_temp & "<li>"
Item_classid = I
Filename = "Index" & item_classid & ". htm"
Filepath = server. mappath ("/") & "\" & filename
Html_temp = html_temp & filepath & "</LI>"
Do_url = "http ://"
Do_url = do_url & request. servervariables ("SERVER_NAME") & "/main/index. asp"
Do_url = do_url &"? Item_classid = "& item_classid
Strurl = do_url
Dim objxmlhttp
Set objxmlhttp = server. Createobject ("Microsoft. XMLHTTP ")
Objxmlhttp. Open "get", strurl, false
Objxmlhttp. Send ()
Dim binfiledata
Binfiledata = objxmlhttp. responsebody
Dim objadostream
Set objadostream = server. Createobject ("ADODB. Stream ")
Objadostream. type = 1
Objadostream. open ()
Objadostream. Write (binfiledata)
Objadostream. savetofile filepath, 2
Objadostream. Close ()
Next
Html_temp = html_temp & "<ul>"
%>
<%
Response. Write ("successfully generated file :")
Response. Write ("<br> ")
Response. Write html_temp
%>

PHP static webpage Generation Method
I have seen a lot of friends posting in various places asking PHP about how to generate a static article system. I have done such a system before, so I would like to talk about 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 ".
2. Static pages.
A static page is a page on the server that contains only HTML, JS, CSS, and other scripts on the client. 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 and perform database access operations to form an HTML language information package. Static pages do not need to be parsed, direct sending without connecting to the database can greatly reduce the pressure on the server, improve the server load capability, and greatly provide the page opening speed and the 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

<HTML>
<Title> {Title} </title>
<Body>
This is a {file} file's templets
</Body>
</Html>

PHP processing:
Templetest. php

<? PHP
$ Title = "http://siyizhu.com test template ";
$ File = "twomax inter test templet, <br> 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.
Well, we have compared the advantages and disadvantages of static pages and dynamic pages. Now let's talk about how to use PHP to generate static files.
Generating static pages in PHP does not refer to the dynamic parsing of PHP, but to outputting HTML pages. Instead, PHP is used to create HTML pages. At the same time, because of the non-writability of HTML, if the HTML we create is modified, We need to delete it and generate it again. (You can also modify the regular expression, but I personally think that it is better to delete and regenerate the regular expression, which is 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 .) Take the previous example as an example. If we modify the last modification, We must generate a static file named test.html under the test directory:

<? PHP
$ Title = "http://siyizhu.com test template ";
$ File = "twomax inter test templet, <br> 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 ("generate File". $ 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 and record the file name. Each time a file is generated, the automatically generated file name is saved to the database. For recommended articles, you only need to point to the page in the specified folder where the static files are stored. Use the PHP operation to process the article list and save it as a string. replace this string when generating 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:

<? PHP
$ Title = "http://siyizhu.com test template ";
$ File = "twomax inter test templet, <br> 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 );
// Starts generating the list
$ List = '';
$ SQL = "select ID, title, filename from article ";
$ Query = mysql_query ($ SQL );
While ($ result = mysql_fetch_array ($ query )){
$ List. = '<a href = '. $ root. $ result ['filename']. 'Target = _ blank> '. $ result ['title']. '</a> <br> ';
}
$ Content. = str_replace ("{articletable}", $ list, $ content );
// The generation list ends.
// 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 ("generate File". $ 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 Article generation are all executed in 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:

<? PHP
$ 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. = '<a href = '. $ root. $ result ['filename']. 'Target = _ blank> '. $ title. '</a> <br> ';
}
$ 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 "Generating File". $ indexpath. "failed! "; // Modify it to echo
}
Fclose ($ handle); // close the pointer
}
Fclose ($ FP );
Die ("generation of paging files is complete. If the generation is incomplete, check the File Permission System and generate a new one! ");
?>

The general idea is that, for example, other data generation, data input and output check, and paging content pointing 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. NET static webpage Generation Method
Environment: Microsoft. NET Framework SDK V1.1
OS: Windows Server 2003 Chinese Version
ASP. NET generate static html pages
The FileSystemObject object used to generate static pages implemented in ASP!
System. Io is involved in. net.
The following is the program code Note: This code is not original! Reference others' code

// Generate an HTML 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 ("An error occurred while generating HTML! ");
}

Template page text.html code

<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML>
<Head>
<Title> showarticle </title>
<Body>
Biaoti
<Br>
Content <br>
Author
</Body>
</Html>
Biaoti
<Br>
Content <br>
Author
</Body>
</Html>

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 to the HTML file. In actual applications, you need to add the database before writing the HTML file.

Collected from outdated forums

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.