Home Backend Development PHP Tutorial Detailed tutorial on generating static pages in php

Detailed tutorial on generating static pages in php

Jul 25, 2016 am 09:05 AM

  1. { title }
  2. this is a { file } file's templets
Copy code

PHP processing: templatetest.php

  1. $title = "Test Template";
  2. $file = "TwoMax Inter test templet,author:Matrix@Two_Max";
  3.  $fp = fopen ("temp.html","r ");
  4. $content = fread ($fp,filesize ("temp.html"));
  5. $content .= str_replace ("{ file }",$file,$content);
  6. $content .= str_replace (" { title }",$title,$content);
  7. echo $content;
  8. ?>
Copy code

  Template parsing processing, that is, filling (content) with the results obtained after PHP script parsing and processing Template processing process. 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.

 How to generate static files with PHP.

  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 of the non-writable nature of HTML, 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.)

PHP fans who have used PHP file operation functions know that there is a file operation function fopen in PHP, which is to open 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:

  1. $title = "Test Template";
  2. $file = "TwoMax Inter test templet,author:Matrix@Two_Max";
  3. $fp = fopen ("temp.html","r ");
  4. $content = fread ($fp,filesize ("temp.html"));
  5. $content .= str_replace ("{ file }",$file,$content);
  6. $content .= str_replace (" { title }",$title,$content);
  7. // echo $content;
  8. $filename = "test/test.html";
  9. $handle = fopen ($filename,"w"); //Open file pointer , create a file
  10. /*
  11. Check whether the file is created and writable
  12. */
  13. if (!is_writable ($filename)){
  14. die ("File: ".$filename." is not writable, please check its properties and try again Try! ");
  15. }
  16. if (!fwrite ($handle,$content)){ //Write information to the file
  17. die ("Generate file".$filename."Failed!");
  18. }
  19. fclose ( $handle); //Close the pointer
  20. die ("Create file".$filename."Success!");
  21. ?>
Copy code

Reference for solutions to common problems: 1. Article list issues: Create a field in the database and record the file name. Each 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 designated 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 tag {articletable} to the table where the article list is placed on the page, and in the PHP processing file:

  1. $title = "Test Template";
  2. $file = "TwoMax Inter test templet,author:Matrix@Two_Max";
  3. $fp = fopen ("temp.html","r ");
  4. $content = fread ($fp,filesize ("temp.html"));
  5. $content .= str_replace ("{ file }",$file,$content);
  6. $content .= str_replace (" { title }",$title,$content);
  7. //Start generating list
  8. $list = '';
  9. $sql = "select id,title,filename from article";
  10. $query = mysql_query ($sql);
  11. while ($result = mysql_fetch_array ($query)){
  12. $list .= ''.$result['title'].'';
  13. }
  14. $content .= str_replace ("{ articletable }",$list, $content);
  15. //End of generating list
  16. // echo $content;
  17. $filename = "test/test.html";
  18. $handle = fopen ($filename,"w"); //Open the file pointer and create File
  19. /*
  20. Check whether the file is created and writable
  21. */
  22. if (!is_writable ($filename)){
  23. die ("File: ".$filename." is not writable, please check its properties and try again! ");
  24. }
  25. if (!fwrite ($handle,$content)){ //Write information to the file
  26. die ("Generate file".$filename."Failed!");
  27. }
  28. fclose ($handle ); //Close the pointer
  29. die ("Create file".$filename."Success!");
  30. ?>
Copy code

Second, paging problem. ​If we specify pagination, there will be 20 articles per page. There are 45 articles in a certain sub-channel list according to the database query. First, we obtain the following parameters through query: 1, the total number of pages; 2, the number of articles per page. The second step, for ($i = 0; $i

  1. $fp = fopen ("temp.html","r");
  2. $content = fread ($fp,filesize ("temp.html"));
  3. $onepage = '20';
  4. $sql = "select id from article where channel='$channelid'";
  5. $query = mysql_query ($sql);
  6. $num = mysql_num_rows ($query);
  7. $allpages = ceil ($num / $onepage);
  8. for ($i = 0;$i<$allpages; $i++){
  9. if ($i == 0){
  10. $indexpath = "index.html";
  11. } else {
  12. $indexpath = "index_".$i."html";
  13. }
  14. $start = $i * $onepage;
  15. $list = '';
  16. $sql_for_page = "select name,filename,title from article where channel='$channelid ' limit $start,$onepage";
  17. $query_for_page = mysql_query ($sql_for_page);
  18. while ($result = $query_for_page){
  19. $list .= ''.$title.'';
  20. }
  21. $content = str_replace ("{ articletable }",$list,$content);
  22. if (is_file ($indexpath)){
  23. @unlink ($indexpath); //If the file already exists, delete it
  24. }
  25. $handle = fopen ($ indexpath,"w"); //Open the file pointer and create the file
  26. /*
  27. Check whether the file is created and writable
  28. */
  29. if (!is_writable ($indexpath)){
  30. echo "File: ".$indexpath ."Not writable, please check its properties and try again!"; //Change to echo
  31. }
  32. if (!fwrite ($handle,$content)){ //Write information to the file
  33. echo "Generate file". $indexpath."Failed!"; //Change to echo
  34. }
  35. fclose ($handle); //Close pointer
  36. }
  37. fclose ($fp);
  38. die ("Generation of paging file is completed. If the generation is incomplete, please Check the file permission system and then regenerate! ");
  39. ?>
Copy code

Other data generation, data input and output checking, paging content pointing, etc. can be added to the page as appropriate.

Articles you may be interested in: Three methods and code details for generating static pages in PHP Example of php generating static page function (php2html) How to generate static pages in php (three functions) Details on templates and caching of static files generated by PHP A class written in php to generate static pages How to automatically generate static pages on a virtual host at regular intervals Two ways to generate static files with php Principle analysis of php generating static html files How to generate static pages using smarty Understand the principle of php generating static HTML files How to generate static pages with PHP Three ways to generate static html files with php



Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles