More detailed PHP generated static page tutorials _php Tips

Source: Internet
Author: User
Tags fread mixed php script
One, PHP script and dynamic page.
PHP script is a server-side scripting, can be embedded and other methods and HTML files mixed, but also class, function encapsulation, such as the form of templates to the user request processing. In any way, the rationale for it is this. The client requests a page-----> Web server to introduce the specified script for processing-----> script is loaded into the server-----> The PHP parser specified by the server parses the script to form an HTML language----> The parsed HTML statement is passed back to the browser as a package. It is not difficult to see that after the page is sent to the browser, PHP does not exist, has been transformed into HTML statements. Customer request for a dynamic file, in fact, there is no real file exists there, PHP is parsed into a corresponding page, and then sent back to the browser. This type of page processing is called a "dynamic page".
two, static page.
A static page is a page that does exist on the server side with only HTML and client-run scripts such as JS,CSS. The way it's handled is. The client requests that a page----> Web server confirm and load a page----> the Web server passes the page back to the browser as a package. By this process, we compare the dynamic page, you can square now. Dynamic pages need to be resolved by the PHP parser of the Web server, and usually need to connect the database, do database access operation, then form the HTML language packet, and static page, no need to parse, no need to connect the database, send directly, can greatly reduce the server pressure, improve the server load capacity, Dramatically provide page opening speed and overall site opening speed. However, the disadvantage is that the request cannot be processed dynamically, and the file must exist on the server.
third, template and template parsing.
The template is not yet populated with the content HTML file. For example:
Temp.html
Code:
Copy Code code as follows:

<HTML>
<title>{TITLE}</title>
<BODY>
This is a {file} file ' s templets
</BODY>
</HTML>
PHP Processing:
templetest.php
Code:
$title = "Tuo mai 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, the PHP script will be resolved after processing the results of the fill (content) into the template processing process. Typically, the use of template classes. At present, the more popular template parsing class has phplib,smarty,fastsmarty and so on. The rationale for template parsing is usually replacement. Also some programmers are accustomed to the judgment, loop and other processing into the template file, with the Analytic class processing, the typical application of the block concept, simply for a circular processing. By the PHP script to specify the number of cycles, how to loop generation, and then by the template parsing class to implement these operations.
OK, compared to the static page and dynamic page of their pros and cons, now we say, how to use PHP to generate static files.
PHP generated static page does not refer to PHP dynamic parsing, output HTML page, but refers to the creation of HTML pages in PHP. Also because the HTML is not writable, we create HTML if there is a modification, you need to delete the rebuild can be. (Of course, you can also choose to modify it, but personally think that it is better to delete the regeneration faster, some outweigh the gains.) )
Anyway PHP fans who have used PHP file manipulation functions know that PHP has a file operation function fopen, that is, open the file. If the file does not exist, attempt to create it. This is the rationale that PHP can use to create HTML files. You can create a file as long as the folder that holds the HTML file has write permissions (that is, permission definition 0777). (For Unix systems, the win system is not considered.) Still, for example, if we modify the last sentence and specify that a static file named test.html be generated under the test directory:
Code:
Copy Code code as follows:

<?php
$title = "Tuo mai 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 file pointer, create file
/*
To check whether a file is created and writable
*/
if (!is_writable ($filename)) {
Die ("File:". $filename. " 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! ");
?>

   Common problem solutions in practical applications reference:
   One, the article List question:
  
Create a field in the database, record the file name, each generation of a file, the automatically generated file name is stored in the database, for the recommended article, just point to the folder that holds the static file in the designated folders that page. Use PHP to manipulate the list of articles, save as a string, and replace this string when generating a page. For example, a table that places a list of articles in a page adds tag {articletable}, and in a PHP processing file:
Code:
Copy Code code as follows:

<?php
$title = "Tuo mai 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);
Build list Start
$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 Build list
Echo $content;
$filename = "test/test.html";
$handle = fopen ($filename, "w"); Open file pointer, create file
/*
To check whether a file is created and writable
*/
if (!is_writable ($filename)) {
Die ("File:". $filename. " 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! ");
?>

   two, paging problem.
If we specify pagination, each page is 20 pieces. A channel list of the article through the database query for 45, then, first of all, we get the following parameters through the query: 1, the total number of pages, 2, per page. The second step, for ($i = 0; $i < allpages $i + +), page element acquisition, analysis, and article generation, are executed in this loop. The difference is that die ("Create file". $filename. " Success! This sentence is removed and put into the loop after the display, because the statement will abort the program execution. Cases:
Code:
Copy Code code 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 the
}
$handle = fopen ($indexpath, "w"); Open file pointer, create file
/*
To check whether a file is created and writable
*/
if (!is_writable ($indexpath)) {
echo "File:". $indexpath. " Not writable, please check its properties and try again! "; Modify to Echo
}
if (!fwrite ($handle, $content)) {//write information to file
echo "Generate file". $indexpath. " Failed! "; Modify to Echo
}
Fclose ($handle); Close pointer
}
Fclose ($FP);
Die ("The Raw content page file completes, if the build is not complete, please check the file permission system to regenerate!" ");
?>

In general, such as other data generation, data input and output check, paging content, etc. can be added to the page as appropriate.
In the actual article system processing process, there are many questions to consider, and dynamic page differences, there are many places to pay attention to. But the general idea is so, other aspects can be extrapolate.
Creating a template framework for static web sites with PHP
Templates can improve the structure of your site. This article explains how to use templates to control page layouts in a Web site composed of a large number of static HTML pages through a new feature and template class in PHP 4.
Outline:
===================================
Detach functionality and layout
Avoid page element duplication
Template framework for static web sites
===================================
detach functionality and layout
First, let's take a look at the two main purposes of applying the template:
Detach function (PHP) and layout (HTML)
Avoid page element duplication
The first is to talk about the most, and it envisions a scenario where a group of programmers write PHP scripts to generate page content, while another group of designers design HTML and graphics to control the final appearance of the page. The basic idea of separating functions and layouts is to enable both groups to write and use separate sets of files: programmers only care about files that contain only PHP code, and don't care about the appearance of the page
, and page designers can design the page layout with their most familiar visual editor without having to worry about breaking any PHP code embedded in the page.
If you've ever seen a few tutorials about PHP templates, you should already understand how the templates work. Consider a simple part of the page: the top of the page is the header, the left is the navigation bar, and the rest is the content area. This web site can have the following template files:
Copy Code code as follows:

<!--main.htm-->
<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>
You can see how pages are constructed from these templates: The main template controls the layout of the entire page; header templates and LeftNav templates control the common elements of the page. The identifier inside the curly brace "{}" is a content placeholder. The main advantage of using templates is that interface designers can edit them as they wish, such as setting fonts, modifying colors and graphics, or completely changing the layout of a page. Interface designers can edit these pages with any normal HTML editor or Visual tool, because they contain only HTML code and no PHP code.
The PHP code is saved in a separate file, which is the file that is 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 some sort of calculation. Here is an example:
Copy Code code as follows:

<?php
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 is set $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 are using the popular Fasttemplate template class, but the basic idea is the same for many other template classes. First you instantiate a class, tell it where to find the template file and which template file corresponds to which part of the page, then generate the page content, give the result the identifier of the content, then, in turn, parse each template file, the template class will perform the necessary substitution operations, and finally output the parsing results to the browser.
This file is composed entirely of PHP code, does not contain any HTML code, this is its biggest advantage. Now, PHP programmers can focus on writing the code that generates the page content without having to worry about how to generate HTML to properly format the final page.
You can use this method and the above file to construct a complete Web site. If the PHP code is based on the query string in the URL to generate the page content, 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 advantage to using 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 to the left of all pages of the site by simply editing the template file.
Avoid page element duplication
"It's really good," You might think, "My site is mostly composed of a lot of static pages." Now that I can remove their public parts from all the pages, it's too much trouble to update the public parts. In the future, I can create a unified page layout that is easy to maintain with templates. "But things are not so simple," a lot of static pages say the problem lies.
Please consider the above example. This example actually has only one example.php page, and it is able to generate all the pages of the entire site because it uses the query string in the URL to dynamically construct the page from information sources such as databases.
Most of us are running websites that don't necessarily have database support. Most of our site is composed of static pages, and then use PHP here, there are some dynamic features, such as search engines, feedback forms. So how do you apply a template on such a Web site?
The easiest way to do this is to copy a PHP file for each page,
Then, in each page, the variables that represent the content in the PHP code are set to the appropriate page content. For example, suppose you have three pages that are home, about (about), and products (product), and we can generate them separately with three files. The contents of these three files are as follows:
Copy Code code 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>

<p> hope you can 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 replicate these complex, template-related PHP code for each page, which is as difficult to maintain as repeating common page elements; now the files are mixed with HTML and PHP code; Assigning values to content variables 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 from the HTML content, although we can't remove all the HTML content from the file, but we can move out most of the PHP code.
Template framework for static web sites
First, we write template files for all the common elements of the page as well as the overall layout of the page, and then remove the public parts from all the pages, leaving only the content of the page, followed by adding three lines of PHP code to each page, as follows:
Copy Code code as follows:

<?php
<!--home.php-->
<?php require (' prepend.php ');?>
<?php Pagestart (' home ');?>
<p> Welcome Visit </p>

<p> hope you can enjoy this website </p>
<?php pagefinish ();?>
?>

This approach basically solves the various problems mentioned earlier. Now there are only three lines of PHP code in the file, and no single line of code is directly involved in the template, so it's very unlikely to change the code. In addition, because the HTML content is outside the PHP tag, there is no special character handling 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 of 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 to the browser.
How did this happen? Why is the HTML in the file not sent to the browser before calling the Pagefinish function? The answer is a new feature of PHP 4 that allows you to intercept output to a browser in a buffer. Let's look at Prepend.php's specific code:
Copy Code code as follows:

<?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 a template instance, and then enables output caching. Thereafter, all HTML content from the page itself will go into the cache. The Pagefinish function takes out the contents of the cache and then specifies the contents in the template object, finally parsing the template and outputting the completed page.
This is the entire template framework of the whole process of work. First write the template that contains the common elements of each page of the site, and then remove all the common page layout codes from all the pages and replace them with three lines of PHP code that never changes. and add the Fasttemplate class file and prepend.php to the include path, so you get a Web site where the page layout can be centrally controlled, it has better reliability and maintainability, and extensive changes at the site level become quite easy.
This download package contains
A running example Web site that has a code comment that is more detailed than the previous code comment. The Fasttemplate class can be found in http://www.thewebmasters.net/, the latest version number is 1.1.0, and there is a small patch to keep the class running correctly in PHP 4. The class in the download code for this article has been modified by the patch.
PHP easy to generate static page
Copy Code code as follows:

<?php
/*
* FileName: index.php
*/
Require "conn.php";
$query = "SELECT * FROM News ORDER by datetime DESC";
$result = mysql_query ($query);
?>
<meta http-equiv= "Content-type" content= "text/html; charset=?????? " >
<title>NEWS</title>
<body>
<table width= "border=" 1 "align=" Center ">
<tr>
<td> title </td>
&LT;TD width= > 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 news </a></td>
</tr>
</table>
</body>

Copy Code code as follows:

<?php
/*
FileName: addnews.php
Easy dynamic add generate static News page
#
# The structure of the table ' News '
#
CREATE TABLE ' News ' (
' NewSID ' int (one) not NULL auto_increment,
' title ' varchar 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 for generating static web pages in PHP
In recent years, the World Wide Web (also known as Global Information Network, WWW) has been changing the face of information processing technology. The web has quickly become an effective medium for people and business to communicate and collaborate. Almost all information technology areas are generally influenced by the web. Web Access brings more users and more data, which means more pressure on servers and databases and end users getting slower and faster response times. Web Dynamic page Surface statics should be a more practical and economical option than increasing the CPU, disk drives, and memory to keep up with this growing demand.

The implementation function of the Dynamic Web Web page static with PHP is shown in functions like function gen_static_file ()

Copy Code code as follows:

function Gen_static_file ($program, $filename)
{
$program 1= "/usr/local/apache/htdocs/php/". $program;
$filename 1 = "/usr/local/apache/htdocs/static_html/". $filename;
$cmd _str = "/usr/local/php4/bin/php". $program 1. " } " . $filename 1. " ";
System ($cmd _str);
Echo $filename. "Generated.〈br〉";
}


This function is the key to the implementation of static, that is, the PHP dynamic page program is not sent to the browser, but entered into a file named $filename (see Figure 2). Two parameters in the $program is a PHP dynamic page program, $filename is the name of the generated static page (can be based on the need to make their own naming rules, this is important, see below),/usr/local/php4/bin/ PHP is the part of PHP that has the function of inputting programs into files, and system is the function of executing external commands in PHP. We can also see that all the PHP programs that generate dynamic pages should be placed in the/php/directory, and all new static pages will appear in the/static_html/directory (these paths can be set according to the specific needs).

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

Copy Code code as follows:

function gen_college_static ()
{
for ($i = 0; $i 〈= $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);
}


From this function we can see that by calling the function Gen_static_file (), college_static.php has been statically transformed into 33 static pages college.static0.html~ College.static33.html, where $filename will change as $i changes. Of course, can also be directly from the database to control the number of static pages generated and name, other programs to generate static page calls should be consistent with 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.