I saw many friends posting in various places asking how to generate a static article system in PHP. I have built such a system before, so I would like to share some opinions for your reference. Band of Brothers PHP training will first review some basic concepts.
1. PHP scripts and dynamic pages.
PHP script is a server-side script program that can be mixed with HTML files through methods such as embedding, or it can process user requests in the form of templates in the form of classes, function encapsulation, etc. One way or another, the basics of it are this. The client makes a request for a certain page -----> The WEB server introduces the specified corresponding script for processing -----> The script is loaded into the server -----> PHP parsing specified by the server The script is parsed by the browser to form HTML language form----> The parsed HTML statement is sent back to the browser in the form of a package. It is not difficult to see from this that after the page is sent to the browser, PHP no longer exists and has been converted and parsed into HTML statements. The client request is a dynamic file. In fact, there is no real file there. PHP parses it into the corresponding page and then sends it back to the browser. This way of handling pages is called "dynamic pages".
Second, static page.
Static pages refer to pages that actually exist on the server side and only contain HTML and JS, CSS and other client-side scripts. The way it is handled is. The client makes a request for a certain page----> The WEB server confirms and loads a certain page----> The WEB server passes the page back to the browser in the form of a package. From this process, we can compare the dynamic pages and we can see. Dynamic pages need to be parsed by the PHP parser of the WEB server, and usually need to connect to the database and perform database access operations before they can form an HTML language information package; while static pages do not need to be parsed or connected to the database, and can be sent directly, which can greatly Reduce server pressure, improve server load capacity, and greatly improve page opening speed and overall website opening speed. But its disadvantage is that the request cannot be processed dynamically, and the file must actually exist on the server.
Three, templates and template analysis.
The template means that the content html file has not yet been filled in. For example:
temp.html
PHP processing:
templatetest.php
test templet,
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 is the process of filling (content) into the template with the results obtained after the PHP script parsing and processing. 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.
Okay, after comparing the advantages and disadvantages of static pages and dynamic pages, now let’s talk about how to use PHP to generate static files.
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.)
Getting back to the subject. PHP fans who have used PHP file operation functions know that there is a file operation function fopen in PHP, which opens 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:
$title = "http://siyizhu.com test template";
$file = "TwoMax Inter test templet,
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 the file pointer and create the file
/*
Check whether the file is created and writable
*/
if (!is_writable ($filename)){
die ("File:" .$filename."Not writable, please check its properties and try again!");
}
if (!fwrite ($handle,$content)){ //Write information to the file
die ("Generate File ".$filename."Failed!");
}
fclose ($handle); //Close pointer
die ("Create file".$filename."Success!");
?>
Reference for solutions to common problems in practical applications:
1. Article list problem:
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 specified 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 mark {articletable} to the table where the article list is placed on the page, and in the PHP processing file:
$title = "http://siyizhu.com test template";
$file = "TwoMax Inter test templet,
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);
// Start generating list
$list = '';
$sql = "select id,title,filename from article";
$query = mysql_query ($sql);
while ($result = mysql_fetch_array ($query)){
$list .= ''.$result['title'].'
';
}
$content .= str_replace ("{articletable}",$list,$content);
// Generate a list End
// echo $content;
$filename = "test/test.html";
$handle = fopen ($filename,"w"); //Open the file pointer and create the file
/*
Check whether the file is created and writable
; fclose ($handle); //Close the pointer
die ("Create file".$filename."Success!");
?>
Second, paging problem.
If we specify pagination, there will be 20 articles per page. There are 45 articles in a certain sub-channel list after 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
$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
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 .= ''.$title.'
';
}
$content = str_replace ("{articletable}",$list,$content);
if (is_file ($indexpath)){
@unlink ($indexpath); //If the file already exists, delete it
}
$handle = fopen ($indexpath,"w"); //Open the file pointer , create file
/*
Check whether the file is created and writable
*/
if (!is_writable ($indexpath)){
echo "File: ".$indexpath." is not writable, please check Attribute it and try again!"; //Change to echo
}
if (!fwrite ($handle,$content)){ //Write information to the file
echo "Generate file".$indexpath." Failed!"; //Modify to echo
}
fclose ($handle); //Close pointer
}
fclose ($fp);
die ("Generation of paging file is completed. If the generation is incomplete, Please check the file permission system and regenerate!");
?>
The general idea is this. Other data generation, data input and output checking, pagination content pointing, etc. can be added to the page as appropriate.
In the actual article system processing process, there are still many issues to be considered. There are many differences between www.lampbrother.net and dynamic pages that need to be paid attention to. But the general idea is this, and other aspects can be drawn by analogy.

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

Fibers was introduced in PHP8.1, improving concurrent processing capabilities. 1) Fibers is a lightweight concurrency model similar to coroutines. 2) They allow developers to manually control the execution flow of tasks and are suitable for handling I/O-intensive tasks. 3) Using Fibers can write more efficient and responsive code.

The PHP community provides rich resources and support to help developers grow. 1) Resources include official documentation, tutorials, blogs and open source projects such as Laravel and Symfony. 2) Support can be obtained through StackOverflow, Reddit and Slack channels. 3) Development trends can be learned by following RFC. 4) Integration into the community can be achieved through active participation, contribution to code and learning sharing.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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.

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.

Atom editor mac version download
The most popular open source editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),