Home  >  Article  >  Backend Development  >  A more detailed tutorial on generating static pages with PHP_PHP tutorial

A more detailed tutorial on generating static pages with PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:22:10784browse

1. PHP scripts and dynamic pages.
PHP script is a server-side script program that can be mixed with HTML files through methods such as embedding, or it can process user requests in the form of templates in the form of classes, function encapsulation, etc. One way or another, the basics of it are this. The client makes a request for a certain page -----> The WEB server introduces the designated corresponding script for processing -----> The script is loaded into the server -----> PHP parsing specified by the server The script is parsed by the browser to form HTML language form----> The parsed HTML statement is sent back to the browser in the form of a package. It is not difficult to see from this that after the page is sent to the browser, PHP no longer exists and has been converted and parsed into HTML statements. The client request is a dynamic file. In fact, there is no real file there. PHP parses it into the corresponding page and then sends it back to the browser. This way of handling pages is called "dynamic pages".
Second, static page.
Static pages refer to pages that actually exist on the server side and only contain HTML and JS, CSS and other client-side scripts. The way it is handled is. The client makes a request for a certain page----> The WEB server confirms and loads a certain page----> The WEB server passes the page back to the browser in the form of a package. From this process, we can compare the dynamic pages and we can see. Dynamic pages need to be parsed by the PHP parser of the WEB server, and usually need to connect to the database and perform database access operations before they can form an HTML language information package; while static pages do not need to be parsed or connected to the database, and can be sent directly, which can greatly Reduce server pressure, improve server load capacity, and greatly improve page opening speed and overall website opening speed. But its disadvantage is that the request cannot be processed dynamically, and the file must actually exist on the server.
3. Templates and template analysis.
The template means that the content html file has not yet been filled in. For example:
temp.html
Code:

Copy code The code is as follows:


{ title }

this is a { file } file's templets


PHP processing:
 templetest.php
Code:
$title = "TwoMax 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 processing is the process of filling (content) the results obtained after PHP script parsing into the template. Usually with the help of template classes. Currently, the more popular template parsing classes include phplib, smarty, fastsmarty and so on. The principle of template parsing processing is usually replacement. There are also some programmers who are accustomed to putting judgment, looping and other processing into template files and processing them with parsing classes. The typical application is the block concept, which is simply a loop processing. The PHP script specifies the number of loops, how to loop through, etc., and then the template parsing class implements these operations.
Okay, after comparing the advantages and disadvantages of static pages and dynamic pages, now let’s talk about how to use PHP to generate static files.
PHP generating static pages does not refer to PHP’s dynamic parsing and outputting HTML pages, but refers to using PHP to create HTML pages. At the same time, because HTML is not writable, if the HTML we create is modified, it needs to be deleted and regenerated. (Of course, you can also choose to use regular rules to modify it, but I personally think that it is faster than deleting and regenerating it, which is not worth the gain.)
Return to the topic. PHP fans who have used PHP file operation functions know that there is a file operation function fopen in PHP, which opens a file. If the file does not exist, try to create it. This is the theoretical basis on which PHP can be used to create HTML files. As long as the folder used to store HTML files has write permission (ie permission definition 0777), the file can be created. (For UNIX systems, Win systems do not need to be considered.) Taking the above example as an example, if we modify the last sentence and specify to generate a static file named test.html in the test directory:
Code:
Copy code The code is as follows:

$title = "TwoMax Inter 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 the file
/*
Check whether the file is created and writable
*/
if (!is_writable ($filename)){
die ("File: ".$filename." is 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!");
?>

 Reference for solutions to common problems in practical applications:
 1. Article list problem:
 
Create a field in the database and record the file name. Every time a file is generated, the automatically generated file name is stored in the database. For recommended articles , just point to the page in the specified folder where the static files are stored. Use PHP operations to process the article list, save it as a string, and 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 in the PHP processing file:
Code:
Copy code The code is as follows :

$title = "TwoMax 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);
// Start generating 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);
//End of generating list
// echo $content;
$filename = "test/test.html";
$handle = fopen ($filename,"w"); //Open the file pointer and create the file
/*
 Check whether the file is created and writable
*/
if (!is_writable ($filename)){
die ("File: ".$filename." is not writable, please check Try again after its attributes! ");
}
if (!fwrite ($handle,$content)){ //Write information to the file
die ("Generate file".$filename." Failed! ");
}
fclose ($handle); //Close pointer
die ("Create file".$filename."Success! ");
?>

 Second, the paging problem.
If we specify paging, there will be 20 articles per page. The articles in a certain sub-channel list have The database query is 45, so first we get the following parameters through the query: 1, the total number of pages; 2, the number of articles per page. The second step, for ($i = 0; $i < allpages; $i++), Page element acquisition, analysis, and article generation are all executed in this loop. The difference is that the sentence die ("Create file".$filename."Success!"; is removed and placed in the display after the loop, because this statement will Abort program execution. Example:

Copy 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); //If the file already exists, delete it
}
$handle = fopen ($indexpath,"w"); //Open the file pointer and create the file
/*
Check whether the file is created and writable
*/
if (!is_writable ($indexpath)){
echo "File: ".$indexpath." is not writable, please check its properties Try again! "; //Modify to echo
}
if (!fwrite ($handle,$content)){ //Write information to the file
echo "Generate file".$indexpath." failed! "; //Modify to echo
}
fclose ($handle); //Close pointer
}
fclose ($fp);
die ("Generating paging file is completed, as generated Incomplete, please check the file permission system and regenerate! ");
?>


The general idea is this. Other data generation, data input and output checking, paging content pointing, etc. can be added to the page as appropriate.
In the actual article system processing process, there are still many issues to be considered. There are many differences from dynamic pages that need to be paid attention to. But the general idea is this, and other aspects can be drawn by analogy.
Use PHP to create a template framework for static websites
Templates can improve the structure of the website. This article explains how to use a new feature of PHP 4 and the template class to skillfully use templates to control page layout in a website composed of a large number of static HTML pages.
Outline:
========================================
Separate functionality and layout
Avoid duplication of page elements
Static website template framework
================================== ===
Separating functionality and layout
First let’s look at the two main purposes of applying templates:
Separating functionality (PHP) and layout (HTML)
Avoiding pages Element Repeating
The first purpose is the most talked about purpose, and it envisions a situation where a group of programmers write PHP scripts that generate the content of the page, while another group of designers designs the HTML and graphics to control the page's content. Final appearance. The basic idea of ​​separating functionality and layout is to enable these two groups of people to write and use an independent set of 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
; and page designers You can use the visual editor you are most familiar with to design the page layout without worrying about breaking any PHP code embedded in the page.
If you have watched a few tutorials about PHP templates, then you should already understand how templates work. Consider a simple page part: the top of the page is the header, the left is the navigation bar, and the rest is the content area. This kind of website can have the following template file:
Copy the code The code is as follows:


< ;img src="sitelogo.jpg">


Foo

Bar
You can see how the page is constructed from these templates: the main template controls the layout of the entire page; the header template and leftnav template control Common elements of the page. Identifiers inside curly braces "{}" are content placeholders. The main benefit of using templates is that interface designers can edit these files according to their own wishes, such as setting fonts, modifying colors and graphics, or completely changing the layout of the page. Interface designers can edit these pages with any ordinary HTML editor or visualization tool, because these files only contain HTML code, without any PHP code.
The PHP code is all saved in a separate file, which is the file actually called by the page URL. The web server parses the file through the PHP engine and returns the results to the browser. Generally, PHP code always dynamically generates page content, such as querying a database or performing certain calculations. Here is an example:
Copy code The code is as follows:

// example.php
require('class.FastTemplate.php');
$tpl = new FastTemplate('.');
$tpl->define( array( 'main' => 'main.htm' ,
'header' => 'header.htm',
'leftnav' => 'leftnav.htm' ) );
// The PHP code here sets $content so that it contains the appropriate The page content
$tpl->assign('CONTENT', $content);
$tpl->parse('HEADER', 'header');
$tpl->parse( 'LEFTNAV', 'leftnav');
$tpl->parse('MAIN', 'main');
$tpl->FastPrint('MAIN');
?>

Here we are using the popular FastTemplate template class, but the basic idea is the same for many other template classes. First, you instantiate a class and tell it where to find template files and which template file corresponds to which part of the page; then, generate the page content and assign the result to the content identifier; then, parse each template file in turn, The template class will perform the necessary replacement operations; finally, the parsing results will be output to the browser.
This file is entirely composed of PHP code and does not contain any HTML code, which is its biggest advantage. Now, PHP programmers can focus on writing the code that generates the content of the page, rather than worrying about how to generate the HTML to properly format the final page.
You can use this method and the above files to construct a complete website. If the PHP code generates page content based on the query string in the URL, such as http://www.foo.com/example.php?article=099, you can construct a complete magazine website based on this.
It’s easy to see that there is a second benefit to using templates. As shown in the example above, the navigation bar on the left side of the page is saved as a separate file. We only need to edit this template file to change the navigation bar on the left side of all pages of the website.
Avoid duplication of page elements
“This is really good”, you may be thinking, “My website is mainly composed of a large number of static pages. Now I can remove the common parts of them from all pages and update these The public part is too troublesome. In the future, I can use templates to create a unified page layout that is easy to maintain. "But things are not that simple. "A large number of static pages" reveals the problem.
Please consider the above example. This example actually only has one example.php page. The reason why it can generate all pages of the entire website is that it uses the query string in the URL to dynamically construct pages from information sources such as databases.
Most of us run websites that don’t necessarily have database support. Most of our website is composed of static pages, and then PHP is used to add some dynamic functions here and there, such as search engines, feedback forms, etc. So, how to apply templates on this kind of website?
The simplest method is to copy a PHP file for each page,
and then set the variables representing the content in the PHP code to the appropriate page content in each page. For example, suppose there are three pages, namely home, about, and product. We can use three files to generate them respectively. The contents of these three files are similar to:
Copy code The code is as follows:

/ / home.php
require('class.FastTemplate.php');
$tpl = new FastTemplate('.');
$tpl->define( array( 'main' => 'main.htm',
'header' => 'header.htm',
'leftnav' => 'leftnav.htm' ) );
$content = "

Welcome Visit



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 There are three problems with this approach: we have to duplicate this complex, template-involved PHP code for every page, which makes the page difficult to maintain as well as duplicating common page elements; now the file is a mix of HTML and PHP code; assigning values ​​to content variables will It becomes very difficult because we have to deal with a lot of special characters.
The key to solving this problem is to separate the PHP code and HTML content. Although we cannot delete all the HTML content from the file, we can move out the vast majority of the PHP code.
Static website template framework
First, we write template files for all common elements of the page and the overall layout of the page as before; then delete the common parts from all pages, leaving only the page content; and then add Add three lines of PHP code to each page, as follows:
Copy the code The code is as follows:




Hello


Welcome



< p>Hope you like this website



?>

This method basically solves the various problems mentioned earlier. There are only three lines of PHP code in the file now, and none of them directly refer to the template, so the possibility of changing this code is extremely slim. In addition, since the HTML content is outside the PHP markup, there is no problem with handling special characters. 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 necessary template-related PHP code. The pageStart function sets the template object and page title, and the pageFinish function parses the template and generates the result and sends it to the browser.
How is this achieved? Why is the HTML in the file not sent to the browser until the pageFinish function is called? The answer lies in a new feature of PHP 4, which allows the content output to the browser to be intercepted into a buffer. Let's take a look at the specific code of prepend.php:
Copy the code The code is as follows:

require('class.FastTemplate.php');
function pageStart($title = '') {
GLOBAL $tpl;
$tpl = new FastTemplate('.');
$ tpl->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 up a template instance, and then enables output caching. After this, all HTML content from the page itself will go into the cache. The pageFinish function takes out the contents from the cache, then specifies these contents in the template object, and finally parses the template and outputs the completed page.
This is the entire working process of the entire template framework. First write a template that contains common elements for each page of the website, then delete all common page layout codes from all pages and replace them with three lines of PHP code that never need to be changed; then add the FastTemplate class file and prepend.php to the include path , so that you get a website whose page layout can be controlled centrally, which has better reliability and maintainability, and large-scale modifications at the website level become quite easy.
  The download package for this article contains
a runnable sample website, and 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, and there is a small patch there to ensure that the class runs correctly in PHP 4. The classes in the download code of this article have been corrected by this patch.
PHP easily generates static pages
Copy code 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






< ;/tr>
while($re = mysql_fetch_array($result)){
?>




}
?>




title Publication time
">
Add News




Copy code The code is as follows:

/*
File name: AddNews.php
Simple dynamic addition to generate static news page
#
# 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 '0000-00-00 00:00:00',
KEY `newsid` (`newsid`)
) TYPE=MyISAM AUTO_INCREMENT=11;
*/
?>


Two functions to generate static web pages using PHP
In recent years, the World Wide Web (also known as the Global Information Network, or WWW) has continued to change The face of information processing technology. The Web has quickly become an effective medium for people and businesses to communicate and collaborate. Almost all information technology fields are generally affected by the WEB. Web access brings more users and more data, which means more stress on servers and databases and slower and slower response times for end users. Compared with constantly increasing CPU, disk drives and memory to keep up with this growing demand, staticizing WEB dynamic web pages should be a more practical and economical choice.

The specific implementation function of using PHP to realize the staticization of WEB dynamic web pages is as shown in function gen_static_file()

Copy the code 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;
$cmd_str = "/usr/local/php4/bin/php " . $program1 . " } " . $filename1 . " ";
system($cmd_str);
echo $filename . " generated.〈br〉";
}


This function is the key to achieving staticization , that is, the PHP dynamic page program is not sent to the browser, but is entered into a file named $filename (Figure 2). Among the two parameters, $program is the PHP dynamic page program, $filename is the name of the generated static page (you can make your own naming rules according to your needs, this is very important, see below), /usr/local/php4/bin/php is PHP has the function of inputting programs into files. System is the function in PHP that executes external commands. We can also see that all PHP programs that generate dynamic pages need to be placed in the /php/ directory, and all newly generated static pages will appear in the /static_html/ directory (these paths can be set according to specific needs).

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

Copy code The code is as follows:

function gen_college_static ()
{
for ($i = 0; $i 〈= 32; $i++〉
{
putenv("province_id=" . $i); //*.php file is used when fetching data from the database.
$filename. = "college_static". $i . ".html";
gen_static_file("college_static.php", $filename);
}


From this function we can see By calling the function gen_static_file(), college_static.php is staticized and becomes 33 static pages college.static0.html~college.static33.html. Of course, $filename will change as $I changes. Get the value directly from the database to control the number and name of the generated static pages. The calls of other programs to the generated static pages should be consistent with the naming rules of the static pages.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324773.htmlTechArticle1. PHP scripts and dynamic pages. PHP script is a server-side script program that can be mixed with HTML files through methods such as embedding, or in the form of classes, function encapsulation, etc., in the form of templates...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn