Why can't PHP code directly save HTML files?> PHP static page generation tutorial

Source: Internet
Author: User

Why can't PHP code directly save HTML files ?? & Gt; PHP static page generation tutorial

 the server will parse the file based on its suffix. if it is an HTML file, the server will not parse the syntax, but directly output it to the browser. 2. if a page contains all HTML code without the PHP syntax to be parsed, it is unnecessary to save it as a PHP file, which will reduce the running efficiency. 3. if PHP is required to control the output of HTML code, for example, PHP is required to determine whether A user logs in. if login is required, A is output, and B is output if login is not performed. This requires PHP for control. HTML cannot implement this function

PHP static page generation tutorial, 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:

 {Title}This is a {file} file's templets PHP processing: templetest. php Code:

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:

For solutions to common problems in practical application, see: 1. article list problems: create fields in the database, record file names, and save automatically generated file names to the database for each generated file, 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: 

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:

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.

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) to 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:

 Template example



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:

 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:

 Define (array ('main' => 'main.htm', 'head' => 'header.htm', 'leftnav' => 'leftnav.htm'); $ content ="


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:


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:

 define( array( 'main' => 'main.htm', 'header' => '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


Title Release Date
Add News
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 ().

function gen_static_file($program, $filename) { $program 1= "/usr/local/apache/htdocs/php/" . $program; $filename1 = "/usr/local/apache/htdocs/ static_html/" . $filename; $cmd_str = "/usr/local/php4/bin/php " . $program1 . " } " . $filename1 . " "; system($cmd_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.

Function gen_college_static () {for ($ I = 0; $ I <=32; $ I ++ >{ putenv ("province_id = ". $ I );//*. php files are used 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.

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.