PHP static page generation tutorial. let's review some basic concepts first.
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:
The code is as follows:
{Title}
This is a {file} file's templets
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:
The code is as follows:
$ 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:
The code is as follows:
$ 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:
The 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:
The code is as follows:
Template example
{HEADER} |
{LEFTNAV} |
{CONTENT} |
Foo
Bar
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:
The code is as follows:
// 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:
The code is as follows:
// Home. php
Require ('class. FastTemplate. php ');
$ Tpl = new FastTemplate ('.');
$ Tpl-> define (array ('main' => 'main.htm ',
'Head' => 'header.htm ',
'Leftnav' => 'leftnav.htm '));
$ Content ="
Welcome
Hope you like this website
";
$ 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:
The code is as follows:
Hi!
Welcome
Hope you like this website
?>
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:
The code is as follows:
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 pages
The code is as follows:
/*
* File name: index. php
*/
Require "conn. php ";
$ Query = "select * from news order by datetime desc ";
$ Result = mysql_query ($ query );
?>
NEWS
Title |
Release Date |
While ($ re = mysql_fetch_array ($ result )){?>
"> |
|
}?>
|
Add News |
The code is as follows:
/*
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 ().
The 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.
The 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.