search
HomeBackend DevelopmentPHP TutorialAnalysis of two methods of php static page generation

  1. // Method 1, generate a static page based on the template

  2. // The replaceTemplateString function is used to replace the specified string in the template
  3. function replaceTemplateString($templateString) {
  4. // Use Variables to replace
  5. $title = "Article title";
  6. $body = "Here is the body of the article";
  7. // Replace the string specified in the template
  8. $showString = str_replace ( "%title%", $title, $templateString );
  9. $showString = str_replace ( "%body%", $body, $showString );
  10. // Return the replacement result
  11. return $showString;
  12. }
  13. $template_file = " template.html";

  14. $new_file = "new.html";
  15. // Template file pointer
  16. $template_juBing = fopen ( $template_file, "r" );
  17. // File pointer to be generated
  18. $newFile_juBing = fopen ( $ new_file, "w" );
  19. // Method 1, get the overall template content string, replace it and assign it to the new file

  20. $templateString = fread ( $template_juBing, filesize ( $template_file ) ) ;
  21. $showString = replaceTemplateString ( $templateString ); // Replace the string in the template
  22. fwrite ( $newFile_juBing, $showString ); // Write the replaced content into the generated HTML file
  23. // Method 2, read each line of the template content string in a loop, replace it and add it to the new file in turn

  24. while ( ! feof ( $template_juBing ) ) { // The feof() function detects whether the end of the file has been reached. Returns TRUE if the file pointer reaches the end or an error occurs. Otherwise, return FALSE (including socket timeout and other situations).
  25. $templateString = fgets ( $template_juBing ); // fgets(file,length) reads a line from the file pointer and returns a string up to length - 1 bytes long, including newlines. If length is not specified, it defaults to 1K, or 1024 bytes.
  26. $showString = replaceTemplateString ( $templateString );
  27. fwrite ( $newFile_juBing, $showString ); // When writing content to the opened pointer file for the first time, the original content in the pointer file will be replaced. Before the file pointer is closed, If the fwrite function adds content, it will close the file pointer after the added content
  28. }
  29. */
  30. //
  31. fclose ( $newFile_juBing );
  32. fclose ( $template_juBing ); Relationship with static pages
  33. Usually, after adding a piece of information in the database, a static page of the information is generated, so it is best to add a field in the database table to store the path file name of the corresponding static page to facilitate future modifications. Delete
  34. Template replacement

  35. Generally speaking, if you need to modify the template of a static HTML page, the usual approach is to delete all the generated HTML pages and then recreate the new HTML page. (Or all re-generated)
  36. Dynamic operations on static pages

  37. Sometimes, some dynamic operations also need to be performed on the static HTML pages created. For example, the click-through rate of each news article in the news system is counted.
  38. You can use an image control with a width and height of 0 pixels to hide a php page to implement the page counter function, such as
  39. Analysis of two methods of php static page generation
  40. Static page of link directory

  41. Usually for systems that use static pages, static HTML files are often generated for the directory page of the link list for visitors to browse
  42. Note This is because every addition or deletion of database information will have an impact on the link list. Therefore, every time database information is added or deleted, the static page of the link directory needs to be updated.
  43. Paging design can be completed by creating multiple static pages with linked directories.
  44. */
  45. // Method 2, generated based on the buffer

  46. ob_start (); // When the buffer is activated and there is ob_end_clean(), all non-file output is printed The header information will not be printed to the page, but will be saved in the internal buffer. If there is no ob_end_clean(), the information is both stored in the internal buffer and printed
  47. ?>
Copy code

This is test Output Control

  1. echo "
    this is test Output Control
    ";

  2. include_once 'cache/newFile.php';
  3. $contents = ob_get_contents (); // Get the information stored in the buffer so far. The buffer only saves the content that will be output and printed to the page browser. PHP execution code will not be saved. // $contents = ob_get_clean( ); // Get the information stored in the buffer so far and close the clear buffer
  4. // ob_end_flush();//Output the information stored in the print buffer so far and close it Clear buffer

  5. ob_end_clean (); // Turn off clearing buffer contents

  6. file_put_contents ( $new_file, $contents ); // Write to file Content

  7. ?>
Copy code
2. Template file, template.html

  1. < ;html>
  2. %title%
  3. %title%


  4. %body%
Copy code

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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment