More detailed php generation static pages tutorial

Source: Internet
Author: User
Tags fread

One, PHP script with dynamic page.
PHP script is a server-side script, can be embedded and other methods and HTML files can be mixed, or class, function encapsulation and other forms, in the form of templates to the user request processing. In any way, the rationale for it is such. Requested by the client, requesting 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 in a package way. It is not difficult to see that after the page is sent to the browser, PHP does not exist, has been converted into an HTML statement. Customer requests for a dynamic file, in fact there is no real file exists there, is the PHP parsing the corresponding page, and then sent back to the browser. This kind of page processing is called "Dynamic page".
two, static page.
A static page is a page that does exist on the server side that contains only HTML and client-run scripts such as JS,CSS. The way it's handled is. A request is made by the client requesting a page----> the Web server confirms and loads a page----> the Web server passes the page back to the browser as a package. From this process, we compare the dynamic page, you can now. The dynamic page needs to be parsed by the PHP parser of the Web server, and it is usually necessary to connect the database, make the database access operation, then the HTML language information packet can be formed, while the static page, no need to parse, need not connect the database, send directly, can greatly reduce the server pressure, improve the server load capacity, Dramatically provides page opening speed and website overall opening speed. However, the disadvantage is that the request cannot be processed dynamically and the file must exist on the server.
three, template and template parsing.
The template is not yet populated with the content HTML file. For example:
Temp.html
Code:

Copy the Code code as follows:


<HTML>
<title>{TITLE}</title>
<BODY>
This is a {file} file ' s templets
</BODY>
</HTML>
PHP Processing:
templetest.php
Code:
$title = "Maxtor International test Template";
$file = "Twomax Inter test Templet,
Author:matr[email Protected]_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, will be after the PHP script parsing processing results of filling (content) into the template processing process. Usually with the help of a template class. At present, the more popular template parsing class has phplib,smarty,fastsmarty and so on. The principle of template parsing processing is usually a replacement. Also some programmers are accustomed to judge, loop and other processing into the template file, with the Analytic class processing, the typical application for the block concept, simply for a loop processing. The PHP script specifies the number of cycles, how to iterate, and so on, which is implemented by the template parsing class.
Well, compared to the static page and dynamic page each of the pros and cons, now we say, how to generate static files in PHP.
PHP generated static page does not refer to the dynamic parsing of PHP, the output of HTML pages, but the use of PHP to create HTML pages. At the same time, because the HTML is not writable, we create the HTML if there are changes, we need to delete the regeneration. (Of course, you can also choose to use the regular to modify, but personally think that does not make it easier to delete the regeneration is faster, some outweigh the loss.) )
Anyway PHP Fans with PHP file operation function know that PHP has a file operation function fopen, 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. The file can be created as long as the folder where the HTML file is stored has write permissions (that is, permission definition 0777). (For Unix systems, the win system does not need to be considered.) Still, for example, if we modify the last sentence and specify that a static file named test.html be generated in the test directory:
Code:

Copy the Code code as follows:


<?php
$title = "Maxtor International test Template";
$file = "Twomax Inter test Templet,
Author:[email Protected]_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
/*
Check if the 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! ");
?>


  Solutions for common problems in practical applications reference:
  One, the article List questions:
  
Create a field in the database, record the file name, each file is generated, the automatically generated file name is stored in the database, for the recommended article, just point to the page in the specified folder that holds the static file. Use PHP to manipulate the list of articles, save as a string, and replace this string when generating a page. For example, the table that places the list of articles in the page is added with the tag {articletable}, and in the PHP processing file:
Code:

Copy the Code code as follows:


<?php
$title = "Maxtor International test Template";
$file = "Twomax Inter test Templet,
Author:[email Protected]_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
/*
Check if the 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 paging, 20 articles per page. A sub-channel list of the article through the database query for 45, then, we first through the query to obtain the following parameters: 1, the total number of pages, 2, per page. The second step, for ($i = 0; $i < allpages; $i + +), page element acquisition, analysis, article generation, are executed in this loop. The difference is that die ("Create file". $filename. " Success! This sentence is removed and placed on the display after the loop, because the statement aborts the execution of the program. Cases:
Code:

Copy the 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
/*
Check if the 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 ("Raw ingredient page file complete, such as build incomplete, please check file permissions system after rebuild!") ");
?>


In general, such as other data generation, data input and output inspection, paging content points can be added to the page as appropriate.
In the actual article system processing process, there are many issues to be considered, and dynamic page differences, there are many areas to note. 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, using a new feature and template class for PHP 4.
Outline:
===================================
Separating features and layouts
Avoid duplicate page elements
Template framework for static web sites
===================================
separating features and layouts
First, let's look at the two main purposes of applying a template:
Detach function (PHP) and layout (HTML)
Avoid duplicate page elements
The first is to talk about the most, and it assumes that 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 the two groups of people to write and use separate sets of files: programmers only need to care about files that contain only PHP code, without worrying about the appearance of the page
, and page designers can design a page layout with their most familiar visual editor without worrying about breaking any PHP code embedded in the page.
If you've ever seen a few tutorials on PHP templates, you should already understand how templates work. Consider a simple page detail: The top of the page is the page header, the left side is the navigation bar, and the rest is the content area. This site can have the following template files:

Copy the 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 the pages are constructed from these templates: The main template controls the layout of the entire page, and the header template and the LeftNav template control the common elements of the page. The identifier inside the curly brace "{}" is a content placeholder. The main benefit of using templates is that the interface designer can edit the files as they wish, 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 visualizer, because they contain only HTML code and no PHP code.
The PHP code is all saved to 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. In general, PHP code always dynamically generates page content, such as querying a database or performing some sort of calculation. Here is an example:

Copy the Code code as follows:


<?php
//example.php
require (' class. Fasttemplate.php ');
$tpl = new Fasttemplate ('. ');
$tpl->define (' main ' = ' main.htm ',
' header ' = ' header.htm ',
' leftnav ' = ' leftnav.htm ') );
//PHP code settings Here $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 the basic idea is the same for many other template classes. First you instantiate a class, tell it where to look for the template file and which template file corresponds to which part of the page, then generate the page content, assign the result to the identifier of the content, and then parse each template file in turn, the template class will perform the necessary substitution operations, and finally output the parsing results to the browser.
This file is completely made up of PHP code and does not contain any HTML code, which is its greatest advantage. Now, PHP programmers can focus on writing code that generates page content, rather than worrying 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 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 full magazine website accordingly.
It is easy to see that there is a second benefit to adopting a template. As shown in the example above, the navigation bar on the left side of the page is saved separately as a file, and we can simply edit this template file to change the navigation bar on the left side of all pages of the site.
Avoid repeating page elements
"This is really good," You might think, "My site is mainly composed of a large number of static pages." Now that I can remove the public parts from all the pages, it's too much trouble to update the public parts. Later I can use the template to create a very easy to maintain a unified page layout. "But it's not that simple," a lot of static pages "are going to be the problem," he said.
Please consider the example above. This example actually has only one example.php page, it can generate all the pages of the whole site, because it takes advantage of the query string in the URL to dynamically construct the page from information sources such as databases.
Most of US run web sites that don't necessarily have database support. Most of our sites are made up of static pages, and then we use PHP to add dynamic features, such as search engines, feedback forms, and so on. So, how to apply a template on such a website?
The simplest way is to copy a PHP file for each page,
and then set the variable in the PHP code to the appropriate page content on each page. For example, suppose you have three pages, which are home, about, and product, and we can generate them in three separate files. The contents of these three files are classes such as:

Copy the Code code as follows:


<?php
home.php
Require (' class. Fasttemplate.php ');
$TPL = new Fasttemplate ('. ');
$TPL->define (' main ' = ' main.htm ',
' Header ' = ' header.htm ',
' LeftNav ' = ' leftnav.htm ');
$content = "<p> Welcome access </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 makes the page difficult to maintain, just like repeating common page elements, and now the files are mixed with HTML and PHP code, and 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 of the vast majority of PHP code.
Template framework for static web sites
First, we write the template file for all the common elements of the page and the overall layout of the page as before, then delete the public section from all the pages, leaving only the page content, and then add three lines of PHP code to each page, as follows:

Copy the 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 line of code directly touches the template, so it is very unlikely to change the code. In addition, because the HTML content is outside the PHP tag, there is no processing problem with 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 the necessary PHP code related to the template. Where the Pagestart function sets the template object as well as the page title, the Pagefinish function resolves the template and generates the result to send to the browser.
How is this implemented? Why is the HTML in the file not sent to the browser before calling the Pagefinish function? The answer lies in a new PHP 4 feature that allows the content of the output to the browser to be intercepted into the buffer. Let's take a look at the specific code for prepend.php:

Copy the Code code as follows:


<?php
require (' class. Fasttemplate.php ');
Function Pagestart ($title = ") {
GLOBAL $tpl;
$tpl = new Fasttemplate ('. ');
$tpl->define (' 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. Thereafter, all HTML content from the page itself is entered 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 finished page.
This is the whole process of working with the template framework. Start by writing a template that contains the common elements of each page of the site, and then remove all common page layout codes from all pages, replacing them with three lines of PHP code that never needs to be changed and add the Fasttemplate class files and prepend.php to the include path, so you get a Web site with a page layout that can be centrally controlled, with better reliability and maintainability, and a wide range of site-wide modifications becomes quite easy.
This article downloads a package that contains
A sample web site that can be run, and its code comments are more detailed than the previous code comments. 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 pages

Copy the Code code as follows:


<?php
/*
* file name: 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= "1" border= " align= "center" >
<tr>
<td> title </td>
<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 the Code code as follows:


<?php
/*
File name: addnews.php
Simple dynamic add generate static News page
#
# Structure of the table ' News '
#
CREATE TABLE ' News ' (
' NewSID ' int (one) not NULL auto_increment,
' title ' varchar (+) not NULL default ' ',
' Content ' text is 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, or WWW) has changed the face of information processing technology. The web has quickly become an effective medium and is suitable for people and business communication and collaboration. Almost all of the information technology areas are generally affected by the web. Web Access brings more users and more data, which means more pressure on servers and databases and slower response times for end users. Web Dynamic Web Surface statics should be a more practical and cost-effective alternative to increasing CPU, disk drives, and memory to keep up with this growing demand.

Implement the concrete implementation function of Web Dynamic Web page static using PHP as shown in function Gen_static_file ()

Copy the 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 instead entered into a file named $filename (2). Two parameters $program is a PHP dynamic page program, $filename is the name of the generated static page (it is important to make the naming rules on your own, as you see below),/usr/local/php4/bin/ PHP is a part of PHP that has the ability to program input files, and the system is a function of executing external commands in PHP. 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 the specific needs).

Let's take a concrete example to see how college_static.php static pages are generated.

Copy the 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 is statically converted into 33 static pages college.static0.html~ College.static33.html, where $filename will change with the change of $i. Of course, you can also directly from the database to control the number and name of the static page generated, other programs on the generated static page calls should be consistent with the naming rules of static pages.


More detailed php generation static pages tutorial

Related Article

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.