search
HomeBackend DevelopmentPHP TutorialDetailed tutorial on generating static pages in php

  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;$iif ($i == 0){
  9. $indexpath = "index.html";
  10. } else {
  11. $indexpath = "index_".$i."html";
  12. }
  13. $start = $i * $onepage;
  14. $list = '';
  15. $sql_for_page = "select name,filename,title from article where channel='$channelid ' limit $start,$onepage";
  16. $query_for_page = mysql_query ($sql_for_page);
  17. while ($result = $query_for_page){
  18. $list .= ''.$title.'';
  19. }
  20. $content = str_replace ("{ articletable }",$list,$content);
  21. if (is_file ($indexpath)){
  22. @unlink ($indexpath); //If the file already exists, delete it
  23. }
  24. $handle = fopen ($ indexpath,"w"); //Open the file pointer and create the file
  25. /*
  26. Check whether the file is created and writable
  27. */
  28. if (!is_writable ($indexpath)){
  29. echo "File: ".$indexpath ."Not writable, please check its properties and try again!"; //Change to echo
  30. }
  31. if (!fwrite ($handle,$content)){ //Write information to the file
  32. echo "Generate file". $indexpath."Failed!"; //Change to echo
  33. }
  34. fclose ($handle); //Close pointer
  35. }
  36. fclose ($fp);
  37. die ("Generation of paging file is completed. If the generation is incomplete, please Check the file permission system and then regenerate! ");
  38. ?>
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
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
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.