Generate static page encyclopedia [asp/php/aspx]_asp Basics

Source: Internet
Author: User
Tags fread html page httpcontext php script
How to generate static Web pages by ASP
With the increase in the number of visits to the Web site, each read from the database is the cost of efficiency, many use Access as a database will be more experience, static page add in search, will be given priority. The popular practice on the internet is to write the data source code into the database and then read from the database to generate static surface, so that the invisible room to enlarge the database. Creating a static page directly from an existing ASP page will save you a lot of money.

The following example is the three dynamic pages that will, index.asp?id=1/index.asp?id=2/index.asp?id=3/, respectively, generate the ndex1.htm,index2.htm,index3.htm existence root directory below:


<%
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
%>

How to generate static Web pages in PHP
See a lot of friends in various places post asked PHP to generate static article system method, previously had done such a system, and then talk about some views, for you to reference. Well, let's look at some basic concepts first.
One, PHP script and dynamic page.
PHP script is a server-side scripting, can be embedded and other methods and HTML files mixed, but also class, function encapsulation, such as the form of templates to the user request processing. In any way, the rationale for it is this. The client requests a page-----> Web server to introduce the specified script for processing-----> script is loaded into the server-----> The PHP parser specified by the server parses the script to form an HTML language----> The parsed HTML statement is passed back to the browser as a package. It is not difficult to see that after the page is sent to the browser, PHP does not exist, has been transformed into HTML statements. Customer request for a dynamic file, in fact, there is no real file exists there, PHP is parsed into a corresponding page, and then sent back to the browser. This type of page processing is called a "dynamic page".
Two, static page.
A static page is a page that does exist on the server side with only HTML and client-run scripts such as JS,CSS. The way it's handled is. The client requests that a page----> Web server confirm and load a page----> the Web server passes the page back to the browser as a package. By this process, we compare the dynamic page, you can square now. Dynamic pages need to be resolved by the PHP parser of the Web server, and usually need to connect the database, do database access operation, then form the HTML language packet, and static page, no need to parse, no need to connect the database, send directly, can greatly reduce the server pressure, improve the server load capacity, Dramatically provide page opening speed and overall site opening speed. However, the disadvantage is that the request cannot be processed dynamically, and the file must exist on the server.
Third, template and template parsing.
The template is not yet populated with the content 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 processing, the PHP script will be resolved after processing the results of the fill (content) into the template processing process. Typically, the use of template classes. At present, the more popular template parsing class has phplib,smarty,fastsmarty and so on. The rationale for template parsing is usually replacement. Also some programmers are accustomed to the judgment, loop and other processing into the template file, with the Analytic class processing, the typical application of the block concept, simply for a circular processing. By the PHP script to specify the number of cycles, how to loop generation, and then by the template parsing class to implement these operations.
OK, compared to the static page and dynamic page of their pros and cons, now we say, how to use PHP to generate static files.
PHP generated static page does not refer to PHP dynamic parsing, output HTML page, but refers to the creation of HTML pages in PHP. Also because the HTML is not writable, we create HTML if there is a modification, you need to delete the rebuild can be. (Of course, you can also choose to modify it, but personally think that it is better to delete the regeneration faster, some outweigh the gains.) )
Anyway PHP fans who have used PHP file manipulation functions know that PHP has a file operation function fopen, that is, open the file. If the file does not exist, attempt to create it. This is the rationale that PHP can use to create HTML files. You can create a file as long as the folder that holds the HTML file has write permissions (that is, permission definition 0777). (For Unix systems, the win system is not considered.) Still, for example, if we modify the last sentence and specify that a static file named test.html be generated 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 file pointer, create file
/*
To check whether a file is created and writable
*/
if (!is_writable ($filename)) {
Die ("File:". $filename. " Not writable, please check its properties and try again! ");
}
if (!fwrite ($handle, $content)) {//write information to file
Die ("Generate file". $filename. " Failed! ");
}
Fclose ($handle); Close pointer

Die ("Create file". $filename. " Success! ");
?>
Common problem solutions in practical applications reference:
One, the article List question:
Create a field in the database, record the file name, each generation of a file, the automatically generated file name is stored in the database, for the recommended article, just point to the folder that holds the static file in the designated folders that page. Use PHP to manipulate the list of articles, save as a string, and replace this string when generating a page. For example, a table that places a list of articles in a page adds tag {articletable}, and in a PHP processing file:

<?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);
Build list Start
$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);
End of Build list
Echo $content;
$filename = "test/test.html";
$handle = fopen ($filename, "w"); Open file pointer, create file
/*
To check whether a file is created and writable
*/
if (!is_writable ($filename)) {
Die ("File:". $filename. " Not writable, please check its properties and try again! ");
}
if (!fwrite ($handle, $content)) {//write information to file
Die ("Generate file". $filename. " Failed! ");
}
Fclose ($handle); Close pointer
Die ("Create file". $filename. " Success! ");
?>
Second, paging problem.
If we specify pagination, each page is 20 pieces. A channel list of the article through the database query for 45, then, first of all, we get the following parameters through the query: 1, the total number of pages, 2, per page. The second step, for ($i = 0; $i < allpages $i + +), page element acquisition, analysis, and article generation, are executed in this loop. The difference is that die ("Create file". $filename. " Success! This sentence is removed and put into the loop after the display, because the statement will abort the program execution. Cases:

<?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); If the file already exists, delete the
}
$handle = fopen ($indexpath, "w"); Open file pointer, create file
/*
To check whether a file is created and writable
*/
if (!is_writable ($indexpath)) {
echo "File:". $indexpath. " Not writable, please check its properties and try again! "; Modify to Echo
}
if (!fwrite ($handle, $content)) {//write information to file
echo "Generate file". $indexpath. " Failed! "; Modify to Echo
}
Fclose ($handle); Close pointer
}
Fclose ($FP);
Die ("The Raw content page file completes, if the build is not complete, please check the file permission system to regenerate!" ");
?>
In general, such as other data generation, data input and output check, paging content, etc. can be added to the page as appropriate.
In the actual article system processing process, there are many questions to consider, and dynamic page differences, there are many places to pay attention to. But the general idea is so, other aspects can be extrapolate.

Asp. NET generation of static Web pages
Environment: Microsoft. NET Framework SDK v1.1
Os:windows Server 2003 Chinese version
Asp. NET generates static HTML pages
The FileSystemObject object for generating static pages implemented in ASP!
This type of operation is involved in. NET System.IO
Here is the program code Note: This code is not original! Refer to other people's Code

Generate HTML page
public static bool WriteFile (string strtext,string strcontent,string strauthor)
{
String path = HttpContext.Current.Server.MapPath ("/news/");
Encoding code = encoding.getencoding ("gb2312");
Reading template files
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 (); Reading files
}
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 point, the template file has been read into a variable named str.
Str =str. Replace ("Showarticle", StrText); Showarticle in the template page
str = str. Replace ("Biaoti", StrText);
str = str. Replace ("Content", strcontent);
str = str. Replace ("Author", Strauthor);
Write a file
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 placed in the Conn.CS base class.
Reference note in code to add News: project name is hover

if (Hover.Conn.WriteFilethis.Title.Text.ToString), this. Content.Text.ToString), this. Author.Text.ToString)))
{
Response.Write ("Add success");
}
Else
{
Response.Write ("Generate HTML Error!");
}
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>
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.