PHP static page generation tutorial

Source: Internet
Author: User

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
Code: Copy codeThe Code is as follows: <HTML>
<TITLE> {title} </TITLE>
<BODY>
This is a {file} file's templets
</BODY>
</HTML>
PHP processing:
Templetest. php
Code:
$ Title = "tomai international 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.
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:
Code:Copy codeThe Code is as follows: <? Php
$ Title = "tomai international 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 ("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:
Code:Copy codeThe Code is as follows: <? Php
$ Title = "tomai international 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 );
// Starts generating the 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 );
// 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:
Code:Copy codeThe Code is as follows: $ 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 "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.
Use PHP to create a static website template framework
Templates can improve the website structure. This article describes how to use a new function and template class of PHP 4 to skillfully control page layout in a website composed of a large number of static HTML pages.
Outline:
==========================================
Separation of functions and Layout
Avoid repeated page elements
Static website template framework
==========================================
Separation of functions and Layout
First, let's take a look at the two main purposes of the Application Template:
Separation of functions (PHP) and layout (HTML)
Avoid repeated page elements
The first purpose is to talk the most about it. It assumes that a group of programmers write PHP scripts used to generate page content, at the same time, another group of designers designed HTML and graphics to control the final appearance of the page. The basic idea of separation of functions and layout is to enable the two groups to write and use independent files: programmers only need to care about files that only contain PHP code, and do not need to care about the appearance of the page.
Page designers can use their most familiar visual editors to design the page layout without worrying about cracking any PHP code embedded into the page.
If you have read several tutorials on PHP templates, You should have understood the working mechanism of the template. Consider a simple page: the top of the page is the page header, the left is the navigation bar, and the rest is the content area. Such websites can have the following template files:Copy codeThe Code is as follows: <! -- Main.htm -->
<Html>
<Head> <title> template example </title> <Body>
<Table> <tr> <td >{ HEADER} </td> </tr>
<Tr> <td> {LEFTNAV} </td> <td> {CONTENT} </td> </tr>
</Table>
</Body>

<! -- Header.htm -->

<! -- Leftnav.htm -->
<Br> <a href = "foo"> Foo </a>
<Br> <a href = "bar"> Bar </a>
We can see how the page is constructed by these templates: The main template controls the layout of the entire page; the header template and leftnav template control the public elements of the page. The identifier in the braces "{}" is a content placeholder. The main advantage of using a template is that the interface designer can edit these files as needed, such as setting fonts, changing colors and graphics, or completely changing the page layout. The interface designer can use any common HTML editor or visualization tool to edit these pages, because these files only contain HTML code, without any PHP code.
All PHP code is saved to a separate file. This file is actually called by the page URL. The Web server parses the file through the PHP engine and returns the result to the browser. In general, PHP code always dynamically generates page content, such as querying a database or executing a computing task. The following is an example:Copy codeThe Code is as follows: <? Php
// Example. php
Require ('class. FastTemplate. php ');
$ Tpl = new FastTemplate ('.');
$ Tpl-> define (array ('main' => 'main.htm ',
'Head' => 'header.htm ',
'Leftnav' => 'leftnav.htm '));
// The PHP code here sets $ content to include the appropriate page content
$ Tpl-> assign ('content', $ CONTENT );
$ Tpl-> parse ('header', 'header ');
$ Tpl-> parse ('leftnav', 'leftnav ');
$ Tpl-> parse ('main', 'main ');
$ Tpl-> FastPrint ('main ');
?>

Here we use the popular FastTemplate template class, but its basic idea is the same for many other template classes. First, you instantiate a class and tell it where to find the template file and which template file corresponds to the part of the page. Next, you generate the page content and assign the result to the content identifier; the template files are parsed in sequence, and the template class performs the necessary replacement operations. Finally, the parsing result is output to the browser.
This file is completely composed of PHP code and does not contain any HTML code. This is its biggest advantage. Now, PHP programmers can focus on writing code that generates page content without worrying about how to generate HTML to correctly format the final page.
You can use this method to construct a complete website with the above files. If PHP code generates page content based on query strings in URLs, such as http://www.foo.com/example.php? Article = 099. You can construct a complete magazine website accordingly.
It is easy to see that there is a second benefit to using templates. As shown in the preceding example, the navigation bar on the left of the page is saved as a file. You only need to edit this template file to change the navigation bar on the left of all pages of the website.
Avoid repeated page elements
"This is really good," you may think, "My website is mainly composed of a large number of static pages. Now I can delete their public parts from all pages. It is too much trouble to update these public parts. In the future, I can use a template to create a uniform page layout that is easy to maintain ." But it is not that simple. "A large number of static pages" indicate the problem.
Consider the example above. In this example, there is actually only one example. php page. It can generate all the pages of the entire website because it uses the query string in the URL to dynamically construct the page from information sources such as databases.
Most of us do not necessarily have database support for their websites. Most of our websites are composed of static pages, and PHP is used to add dynamic functions, such as search engines and feedback forms. So, how to apply templates on such websites?
The simplest way is to copy a PHP file for each page,
Then, set the variables in the PHP code that represent the content in each page to the appropriate page content. For example, suppose there are three pages: home, about, and product. We can use three files to generate them respectively. The content of these three files is similar:Copy codeThe Code is as follows: <? Php
// Home. php
Require ('class. FastTemplate. php ');
$ Tpl = new FastTemplate ('.');
$ Tpl-> define (array ('main' => 'main.htm ',
'Head' => 'header.htm ',
'Leftnav' => 'leftnav.htm '));
$ Content = "<p> welcome </p>

<P> hope you like this website </p> ";
$ Tpl-> assign ('content', $ CONTENT );
$ Tpl-> parse ('header', 'header ');
$ Tpl-> parse ('leftnav', 'leftnav ');
$ Tpl-> parse ('main', 'main ');
$ Tpl-> FastPrint ('main ');
?>

Obviously, this method has three problems: we must copy these complicated PHP Code involving the template for each page, which makes the page difficult to maintain just like repeated public page elements; now the file is mixed with HTML and PHP code. It is very difficult to assign values to content variables because we have to deal with a large number of special characters.
The key to solving this problem lies in the separation of PHP code and HTML content. Although we cannot delete all HTML content from the file, we can remove the vast majority of PHP code.
Static website template framework
First, we will write a template file for all the common page elements and the overall layout of the page as before. Then, we will delete the public part from all the pages, leaving only the page content; next, add three lines of PHP code to each page, as shown below:Copy codeThe Code is as follows: <? Php
<! -- Home. php -->
<? Php require ('prepend. php');?>
<? Php pageStart ('home');?>
<H1> Hello <P> welcome </p>

<P> hope you like this website </p>
<? Php pageFinish ();?>
?>

This method basically solves the various problems mentioned above. Currently, there are only three lines of PHP code in the file, and no line of code is directly related to the template. Therefore, there is little possibility to modify the code. In addition, because the HTML content is outside the PHP tag, there is no special character processing problem. We can easily add these three lines of PHP code to all static HTML pages.
The require function introduces a PHP file that contains all the required PHP Code related to the template. The pageStart function sets the template object and page title. The pageFinish function parses the template and generates the result and sends it to the browser.
How is this implemented? Why does the HTML in the file not be sent to the browser before calling the pageFinish function? The answer is a new function of PHP 4 that allows the interception of the content output to the browser into the buffer zone. Let's take a look at the specific code of prepend. php:Copy codeThe Code is as follows: <? Php
Require ('class. FastTemplate. php ');
Function pageStart ($ title = ''){
GLOBAL $ tpl;
$ Tpl = new FastTemplate ('.');
$ Tpl-> define (array ('main' => 'main.htm ',
'Head' => 'header.htm ',
'Leftnav' => 'leftnav.htm '));
$ Tpl-> assign ('title', $ TITLE );
Ob_start ();
}
Function pageFinish (){
GLOBAL $ tpl;
$ Content = ob_get_contents ();
Ob_end_clean ();
$ Tpl-> assign ('content', $ CONTENT );
$ Tpl-> parse ('header', 'header ');
$ Tpl-> parse ('leftnav', 'leftnav ');
$ Tpl-> parse ('main', 'main ');
$ Tpl-> FastPrint ('main ');
}
?>

The pageStart function first creates and sets a template instance, and then enables the output cache. After that, all HTML content from the page itself will be cached. The pageFinish function retrieves the cached content, specifies the content in the template object, parses the template, and outputs the completed page.
This is the entire template framework process. First, write a template containing the public elements of each page of the website, and then delete all public page layout code from all pages, replacing it with three lines of PHP code that will never be changed; then, set the FastTemplate class file and prepend. add php to the inclusion path, so that you can get a website with centralized control of the page layout. It has better reliability and maintainability, and it also becomes quite easy to modify a wide range of websites.
The downloaded package contains
For a running sample website, its code comments are more detailed than the previous code comments. The FastTemplate class can be found at http://www.thewebmasters.net/. the latest version number is 1.1.0. There is also a small patch used to ensure that the class runs correctly in PHP 4. The classes in the downloaded code in this article have been corrected by the patch.
PHP easily generates static pagesCopy codeThe Code is as follows: <? Php
/*
* File name: index. php
*/
Require "conn. php ";
$ Query = "select * from news order by datetime desc ";
$ Result = mysql_query ($ query );
?>
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = ?????? ">
<Title> NEWS </title>
</Head>
<Body>
<Table width = "500" border = "1" align = "center">
<Tr>
<Td> title </td>
<Td width = "200"> release date </td>
</Tr>
<?
While ($ re = mysql_fetch_array ($ result )){
?>
<Tr>
<Td> <a href = "<? = $ Re ["newsid"]. ". html"?> "> <? = $ Re ["title"]?> </A> </td>
<Td> <? = $ Re ["datetime"]?> </Td>
</Tr>
<?
}
?>
<Tr>
<Td> </td>
<Td> <a href = "addnews. php"> Add news </a> </td>
</Tr>
</Table>
</Body>
</Html>

Copy codeThe Code is as follows: <? Php
/*
File Name: AddNews. php
Simple and dynamic addition and generation of static news pages
#
# Table structure 'News'
#
Create table 'News '(
'Newsid 'int (11) not null auto_increment,
'Title' varchar (100) not null default '',
'Content' text not null,
'Datetime' datetime not null default '2017-00-00 00:00:00 ',
KEY 'newsid' ('newsid ')
) TYPE = MyISAM AUTO_INCREMENT = 11;
*/
?>

Use PHP to generate two functions for static Web pages
In recent years, the World Wide Web (also known as the World Wide Information Network (WWW) has continuously changed the face of information processing technologies. WEB has quickly become an effective medium for people to communicate and collaborate with businesses. Almost all information technology fields are affected by the WEB. Web access brings more users and more data, which means more pressure on servers and databases and slow response speed for end users. Compared with increasing CPU, disk drive, and memory to keep up with this demand, static WEB pages should be a more practical and economical choice.

Use PHP to implement static WEB pages, as shown in function gen_static_file ().

Copy codeThe Code is as follows: function gen_static_file ($ program, $ filename)
{
$ Program 1 = "/usr/local/apache/htdocs/php/". $ program;
$ Filename1 = "/usr/local/apache/htdocs/static_html/". $ filename;
$ Pai_str = "/usr/local/php4/bin/php". $ program1. "}". $ filename1 ."";
System ($ response _str );
Echo $ filename. "generated. <br> 〉";
}

This function is the key to static, that is, the PHP dynamic page program is not sent to the browser, but is input to the file named $ filename (2 ). Among the two parameters, $ program is a PHP dynamic page program, and $ filename is the name of the generated Static Page (you can customize naming rules as needed. This is important, see the following description ), /usr/local/php4/bin/php is a part of PHP that provides the function of inputting program files. System is a function used to execute External commands in PHP. We can also see that all php programs that generate dynamic pages should be placed in the/php/directory, all newly generated static pages will appear in the/static_html/directory (these paths can be set as needed ).

Let's take a specific example to see how the static page of college_static.php is generated.

Copy codeThe Code is as follows: function gen_college_static ()
{
For ($ I = 0; $ I <=32; $ I ++> 〉
{
Putenv ("province_id =". $ I); // * use the PHP file to retrieve data from the database.
$ Filename = "college_static". $ I. ". html ";
Gen_static_file ("college_static.php", $ filename );
}

From this function, we can see that by calling the function gen_static_file (), college_static.php goes through the static state and becomes the 33 page college.static0.html ~ College.static33.html, where $ filename changes with $ I. Of course, you can also take values directly from the database to control the number and name of generated static pages. Other programs should call the generated static pages in the same way as the static page naming rules.

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.