More detailed PHP generates static page tutorials

  • 2020-05-10 17:50:01
  • OfStack

1, PHP scripts and dynamic pages.
PHP script is a kind of server-side script, which can be mixed with HTML files by means of embedding or in the form of classes, function encapsulation or templates to process user requests. In any case, the rationale is this. By the client request, request a 1 page -- > The WEB server is introduced to specify the appropriate script for processing -- > The script is loaded into the server -- > The script is parsed by the PHP parser specified by the server to form the HTML language > The parsed HTML statements are packaged back to the browser. It is not difficult to see that after the page is sent to the browser, PHP does not exist and has been translated and parsed into HTML statements. The client requested a 1 dynamic file, but in fact no real file exists there, which is parsed by PHP into the corresponding page and then sent back to the browser. This type of page processing is called "dynamic pages."
2. Static pages.
Static page refers to the page that only contains HTML and JS, CSS and other client-side running scripts, which does exist on the server side. The way it's handled is. By the client request, request a certain 1 page -- > The WEB server confirms and loads a certain page -- > The WEB server passes the page back to the browser as a package. From this 1 process, we compare 1 dynamic page, can be displayed. Dynamic pages need to be parsed by the PHP parser on the WEB server, and they usually need to be connected to the database for database access operations before HTML language packets can be formed. And static page, no need to parse, no need to connect to the database, directly send, can greatly reduce the pressure on the server, improve the load capacity of the server, greatly provide the page opening speed and the overall website opening speed. The disadvantage is that the request cannot be processed dynamically and the file must actually exist on the server.
3. Template and template analysis.
The template has not yet populated the content html file. Such as:
temp. html
Code:
 
<HTML> 
<TITLE>{ title }</TITLE> 
<BODY> 
this is a { file } file's templets 
</BODY> 
</HTML> 
PHP Processing:  
 templetest.php 
Code: 
$title = " Tamale international testing templates "; 
$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, the process of populating (content) the results of the PHP script parsing into the template. Usually with the help of a template class. The popular template resolution classes are phplib, smarty, fastsmarty, and so on. The principle of template parsing is usually substitution. Some programmers are used to putting judgment, loop and other processing into the template file and using the parse class. The typical application is the concept of block, which is simply a loop. The PHP script specifies the number of loops, how to loop in, and so on, which are then implemented by the template resolution class.
Now that we've compared static pages to dynamic pages, let's talk about how to generate static files using PHP.
PHP generating static pages does not refer to the dynamic parsing of PHP and the output of HTML pages, but rather to the creation of HTML pages with PHP. At the same time, due to the unwritability of HTML, if the HTML we created is modified, we need to delete and regenerate it. (of course, you can choose to use regex to make changes, but I think it would be quicker to delete and regenerate than to do so.)
Anyway. PHP FANS who have used the PHP file manipulation function knows that there is one file manipulation function fopen in PHP, which is to open the 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. Files can be created as long as the folder used to hold HTML files has write permissions (that is, permission definition 0777). (for the UNIX system, the Win system does not need to be considered.) As an example, if we modify the last sentence and specify to generate a static file named test.html in the test directory:
Code:
 
<?php 
$title = " Tamale international testing templates "; 
$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 that the file is created and writable  
*/ 
if (!is_writable ($filename)){ 
die (" File: ".$filename." Cannot write, please check its properties and try again! "); 
} 
if (!fwrite ($handle,$content)){ // Write the information to a file  
die (" Generate the file ".$filename." Failure! "); 
} 
fclose ($handle); // Close the pointer  
die (" Create a file ".$filename." Success! "); 
?> 

Reference for solutions to common problems in practical application:
1. Article list questions:

Create a field in the database, record the file name, and save the automatically generated file name into the database for each file generated. For the recommended article, simply point to the page in the specified folder where the static file is stored. The PHP operation is used to process the list of articles, save as a string, and replace the string when the page is generated. For example, put the tag {articletable} in the table where the list of articles is placed on the page, and in the PHP processing file:
Code:
 
<?php 
$title = " Tamale international testing templates "; 
$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 of generate 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 generated list  
// echo $content; 
$filename = "test/test.html"; 
$handle = fopen ($filename,"w"); // Open the file pointer and create the file  
/* 
 Check that the file is created and writable  
*/ 
if (!is_writable ($filename)){ 
die (" File: ".$filename." Cannot write, please check its properties and try again! "); 
} 
if (!fwrite ($handle,$content)){ // Write the information to a file  
die (" Generate the file ".$filename." Failure! "); 
} 
fclose ($handle); // Close the pointer  
die (" Create a file ".$filename." Success! "); 
?> 

2. Paging problem.
As we specify paging, 20 pages per page. The article in the list of some sub-channels is 45 by database query, then, first of all, we get the following parameters through the query: 1, the total number of pages; 2. Number of pages per page. Step 2, for ($i = 0; $i < allpages; $i++), page element acquisition, analysis, article generation, all are executed in this loop. The difference is, die (" create file ".$filename." success!" ; This sentence is removed and displayed after the loop, because this statement will abort the execution of the program. Ex. :
Code:
 
$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 that the file is created and writable  
*/ 
if (!is_writable ($indexpath)){ 
echo " File: ".$indexpath." Cannot write, please check its properties and try again! "; // Modified to echo 
} 
if (!fwrite ($handle,$content)){ // Write the information to a file  
echo " Generate the file ".$indexpath." Failure! "; // Modified to echo 
} 
fclose ($handle); // Close the pointer  
} 
fclose ($fp); 
die (" The generation of paging files is complete. If the generation is incomplete, please check the file permissions system and rebuild! "); 
?> 

The general idea is like this, which such as other data generation, data input and output check, paging content pointing can be added in the page as appropriate.
In the actual article system processing process, there are still many problems to be considered, and the dynamic page is different, need to pay attention to a lot of places. But that's the general idea. You can get 1 against 3 in other ways.
Use PHP to create a static website template frame
Templates can improve the structure of your site. This article explains how to use templates to control the layout of a web site with a large number of static HTML pages, using one of PHP 4's new features and template classes.
Outline:
===================================
Separate functionality from layout
Avoid page element duplication
Static website template frame
===================================
Separate functionality from layout
First, let's look at the two main purposes of applying templates:
Separation of functions (PHP) and layout (HTML)
Avoid page element duplication
The first goal, the most talked about one, assumes that one group of programmers writes PHP scripts for generating page content, while another group of designers design HTML and graphics to control the final appearance of the page. The basic idea of separating functionality and layout is to enable each group to write and use a separate set of files: programmers only care about files that contain only PHP code, not the appearance of the page
; Page designers, on the other hand, can design page layouts with their most familiar visual editor without worrying about breaking any PHP code embedded in the page.
If you've seen several tutorials on PHP templates, you already know how templates work. Consider a simple page section: the top of the page is the header, the left is the navigation bar, and the rest is the content area. This site can have the following template files:
 
<!-- main.htm --> 
<html> 
<head><title> Template sample </title></head> 
<body> 
<table><tr><td>{HEADER}</td></tr> 
<tr><td>{LEFTNAV}</td><td>{CONTENT}</td></tr> 
</table> 
</body></html> 

< !-- header.htm -- >
< img src="sitelogo.jpg" >
< !-- leftnav.htm -- >
< br > < a href="foo" > Foo < /a >
< br > < a href="bar" > Bar < /a >
You can see how pages are constructed from these templates: the main template controls the layout of the entire page; The header template and leftnav template control the common elements of the page. The identifier inside the curly braces' {} 'is the content placeholder. The main benefit of using templates is that the interface designer can edit these files as he or she wishes, such as setting fonts, changing colors and graphics, or completely changing the layout of the page. The interface designer can edit these pages with any normal HTML editor or visualization tool, because these files contain only the HTML code, not 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. Like 1, the PHP code always generates page content dynamically, such as querying a database or performing some kind of computation. Here's an example:
 
<?php 
// example.php 
require('class.FastTemplate.php'); 
$tpl = new FastTemplate('.'); 
$tpl->define( array( 'main' => 'main.htm', 
'header' => 'header.htm', 
'leftnav' => 'leftnav.htm' ) ); 
//  Here the PHP Code sets $content Make it contain 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 the 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 which part of the page. The next step is to generate the page content and assign the result to the identifier of the content. Then, each template file is parsed in turn, and the template class performs the necessary substitution operations. Finally, the parsing results are output to the browser.
This file consists entirely of the PHP code and does not contain any HTML code, which is its greatest advantage. Now, PHP programmers can focus on writing the code that generates the content of the page without worrying about how to generate HTML to properly format the final page.
You can use this method and the above files to construct a complete website. If the code is based on the query string URL PHP generated page content, such as http: / / www foo. com/example php? article=099, from which you can construct a complete magazine website.
It is easy to see a second benefit to adopting templates. As shown in the example above, the navigation bar on the left side of the page is saved as a single file, and we can change the navigation bar on the left side of all pages of the website by editing this one template file.
Avoid page element duplication
"That's nice," you might think. "my site is mostly made up of a lot of static pages. I can now remove the public parts from all the pages, which are too cumbersome to update. In the future I will be able to use templates to create a consistent layout that is easy to maintain." But it's not that simple. "lots of static pages" tells the story.
Consider the above example. This example actually has only one example.php page, and it generates all the pages for the entire site because it USES the query strings in URL to dynamically construct pages from information sources such as databases.
Most of us don't run websites that have database support. Most of our site is composed of static pages, and then we use PHP to add some dynamic functions here and there, such as search engine, feedback form, etc. So, how do you apply templates to such sites?
The easiest way is to copy one copy of the PHP file per page,
Then, for each page, set the variables representing the content in the PHP code to the appropriate page content. For example, if we have three pages, the home page (home), about (about), and the product (product), we can generate each of them with three files. The contents of these three files are as follows:
 
<?php 
// home.php 
require('class.FastTemplate.php'); 
$tpl = new FastTemplate('.'); 
$tpl->define( array( 'main' => 'main.htm', 
'header' => 'header.htm', 
'leftnav' => 'leftnav.htm' ) ); 
$content = "<p> Welcome to visit </p> 
<img src=\"demo.jpg\"> 
<p> I hope you enjoy this website </p>"; 
$tpl->assign('CONTENT', $content); 
$tpl->parse('HEADER', 'header'); 
$tpl->parse('LEFTNAV', 'leftnav'); 
$tpl->parse('MAIN', 'main'); 
$tpl->FastPrint('MAIN'); 
?> 

Obviously, there are three problems with this approach: we have to copy the complex, template-involved PHP code for every page, which is as difficult to maintain as repeating the public page element 1; Now the file mixes the HTML and PHP codes; Assigning values to content variables becomes very difficult because we have to deal with a large number of special characters.
The key to solving this problem is to separate the PHP code from the HTML content. Although we cannot remove all the HTML content from the file, we can remove most of the PHP code.
Static website template frame
First, we write template files for all page common elements and the overall layout of the page, as in the previous 1; Then remove the common parts from all the pages, leaving only the content. Next, add three lines of PHP code to each page, as follows:
 
<?php 
<!-- home.php --> 
<?php require('prepend.php'); ?> 
<?php pageStart('Home'); ?> 
<h1> hello </h1> 
<p> Welcome to visit </p> 
<img src="demo.jpg"> 
<p> I hope you enjoy this website </p> 
<?php pageFinish(); ?> 
?> 

This approach basically solves the problems mentioned earlier. There are now only three lines of PHP code in the file, and none of the one line directly touches the template, so there is little chance of changing it. In addition, since the HTML content is outside the PHP markup, there are no special character processing issues. We can easily add these three lines of PHP code to all the static HTML pages.
The require function introduces an PHP file that contains all the required PHP code associated with the template. Where the pageStart function sets the template object and the page title, the pageFinish function parses the template and then generates the results and sends them to the browser.
How does this work? Why isn't HTML in the file sent to the browser before the pageFinish function is called? The answer lies in a new feature in PHP 4, which allows output to be intercepted into a buffer. Let's look at the code for prepend.php:
 
<?php 
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, then enables the output cache. After that, all HTML content from the page itself will be cached. The pageFinish function takes the contents of the cache, specifies them in the template object, and finally parses the template and outputs the finished page.
This is how the entire template framework works. First, write a template that contains the common elements of each page of the website. Then, delete all the common page layout code from all pages and replace it with three lines of PHP code that will never be changed. Add FastTemplate and prepend.php to the include path, and you have a site whose layout can be centrally controlled, which has better reliability and maintainability, and which can be easily modified at the site level on a large scale.
The download package for this article includes
A working example web site with more detailed code comments than the previous code comments. FastTemplate class can http: / / www thewebmasters. net/found, is the latest version 1.1.0, there's one used to ensure the class in PHP 4 correct operation of small patches. The classes in the code downloaded with this article have been fixed with this patch.
PHP simply generates static pages
 
<?php 
/* 
*  The 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> The title </td> 
<td width="200"> Release time </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 the news </a></td> 
</tr> 
</table> 
</body> 
</html> 

 
<?php 
/* 
 The file name: AddNews.php 
 Easy dynamic add to generate static news pages  
# 
#  The structure of the table  `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 ; 
*/ 
?> 


Use PHP to generate two functions for a static web page
In recent years, the world wide web (also known as the global information network, or WWW) has been changing the face of information processing technology. WEB has quickly become an effective medium for people and businesses to communicate and collaborate. Almost all information technology fields are generally influenced by WEB. Access to Web leads to more users and more data, which means more stress on servers and databases and slower and slower response times for end users. Rather than constantly adding CPU, disk drives, and memory to keep up with this growing demand, static WEB dynamic web pages should be a more practical and economical option.

The concrete implementation function of static WEB dynamic web page with PHP is 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. The < br > "; 
} 


This function is the key to staticization, where the PHP dynamic pager is not sent to the browser, but is entered into a file named $filename (figure 2). Two parameters of the dynamic page is $program PHP, $filename is to generate a static page name (according to the need to formulate the naming rules, it is very important 1 point, see below), / usr local php4 / bin/php PHP in, which has the function of the program input file parts System PHP is performed in external command function. We can also see that all php programs that generate dynamic pages are in the /php/ directory, and all newly generated static pages are in the /static_html/ directory (these paths can be set as needed).

Let's take a concrete example of how the static page for college_static.php is generated.

 
function gen_college_static () 
{ 
for ($i = 0; $i  The < = 32; $i++ >  
{ 
putenv("province_id=" . $i); //*.php Files are used when fetching data from a database.  
$filename = " college_static". $i . ".html"; 
gen_static_file("college_static.php", $filename); 
} 


We can see from this function by calling the function gen_static_file (), college_static. php through static, turned into a static page 33 college. static0. html ~ college. static33. html, where $filename will change as the change of $I. Of course, you can also directly from the database value, to control the number and name of the generated static pages, other programs to generate static pages should be called and static page naming rule 1.

Related articles: