How to generate static Web pages in PHP

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

<HTML>

<title>{TITLE}</title>

<BODY>

This is a {file} file ' s templets

</BODY>

</HTML>

PHP Processing:

templetest.php

<?php

$title = "http://siyizhu.com test template";

$file = "Twomax Inter test Templet,<br>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, 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:

<?php

$title = "http://siyizhu.com test template";

$file = "Twomax Inter test Templet,<br>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

/*

Check if the file is created and writable

*/

if (!is_writable ($filename)) {

Die ("File:". $filename. " Do not write, check its properties and try again! ");

}

if (!fwrite ($handle, $content)) {//write information to file

Die ("Generate file". $filename. " Failure! ");

}

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:

<?php

$title = "http://siyizhu.com test template";

$file = "Twomax Inter test Templet,<br>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. = ' <a href= '. $root. $result [' filename ']. ' target=_blank> '. $result [' title ']. ' </a><br> ';

}

$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. " Do not write, check its properties and try again! ");

}

if (!fwrite ($handle, $content)) {//write information to file

Die ("Generate file". $filename. " Failure! ");

}

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 in the loop after the display, because the statement will abort the execution of the program. Cases:

<?php

$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. = ' <a href= '. $root. $result [' filename ']. ' target=_blank> '. $title. ' </a><br> ';

}

$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 content page file completed, such as build incomplete, please check file permissions system after regeneration!");

?>

In general, such as other data generation, data input and output inspection, paging content points can be added to the page as appropriate.
  • 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.