SoFunction
Updated on 2025-04-09

PHP dynamic change static principle

As far as I know, there are two ways to output static pages in PHP, one is to use template technology, and the other is to use ob series functions. Both methods seem similar, but in fact, they are different.

The first type: use templates. Currently, there are many templates for PHP, including powerful smarty, and simple and easy-to-use smarttemplate. Each of them has a function to get the output content. The way we generate static pages is to use this function. The advantage of using this method is that the code is clearer and readable.

Here I use smarty as an example to illustrate how to generate static pages
Copy the codeThe code is as follows:
<?php 
require('smarty/'); 
$t = new Smarty; 
$t->assign("title","Hello World!"); 
$content = $t->fetch("templates/"); 
//The fetch() here is a function to obtain the output content. Now the $content variable is the content to be displayed.
$fp = fopen("archives/2005/05/19/", "w"); 
fwrite($fp, $content); 
fclose($fp); 
?>  

The second method:Use the functions of the ob series. The functions used here are mainly ob_start(), ob_end_flush(), and ob_get_content(). Ob_start() means opening the browser buffer. After opening the buffer, all non-file header information from the PHP program will not be sent, but will be saved in the internal buffer until you use ob_end_flush(). The most important function here is ob_get_contents(). The function of this function is to obtain the content of the buffer, which is equivalent to the above fetch(), and the principle is the same. Code:
Copy the codeThe code is as follows:
<?php 
ob_start(); 
echo "Hello World!"; 
$content = ob_get_contents();//Get all the contents of the output of the php page
$fp = fopen("archives/2005/05/19/", "w"); 
fwrite($fp, $content); 
fclose($fp); 
?>