Home > Article > Backend Development > How to modify html files in php
How to modify html files in php: 1. Use the fopen function to open the html file; 2. Use the fread function to read the file content; 3. Read the file size through the filesize function; 4. Modify the html through the fwrite function File content; 5. Use the fclose function to close the open file.
Recommended: "PHP Video Tutorial"
PHP Modify HTMl Template
New knowledge points:
Some PHP file operation functions (fopen, fread, filesize, fwrite, fclose)
fopen (path and file name, opening method) Open file function
fread (open file, end position) Read file content r-read-only w-write a-read-write
filesize (path and file name) Read file size, bytes Unit of measurement
fwrite(path and file name, written content) Write file content
fclose(path and file name) Close an open file
unlink( ) mkdir() delete function
unlink(path and file name) delete file function
mkdir(path and directory name) delete directory function
Previous knowledge points:
foreach() traversal function
$str_replace() replacement function function
Code display:
Template tmp.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>标题:{title}</title> </head> <body> <!-- 这是一个html模板 --> 内容:{content} </body> </html>
Generate new HTMl operation: html.php
<? $fp = fopen("tmp.html", "r"); // 读取文件的全部内容 $str = fread($fp, filesize("tmp.html")); // 替换文件内容 $str = str_replace("{title}", "今日新闻", $str); $str = str_replace("{content}", "今日新闻要点", $str); fclose($fp); // 只写方式打开文件 $handle = fopen("news.html","w"); fwrite($handle, $str); fclose($handle); echo("生成成功"); ?>
In practice, if you need to generate html files in batches, you can use the following method:
<? $array = array(array("今日新闻","国家医疗改革"),array("昨日回顾","日本福岛9.1级地震")); foreach ($array as $key => $value) { // 只读方式打开文件 $fp = fopen("tmp.html", "r"); // 读取文件的全部内容 $str = fread($fp, filesize("tmp.html")); // 替换文件内容 $str = str_replace("{title}",$value[0], $str); $str = str_replace("{content}", $value[1], $str); fclose($fp); // 只写方式打开文件 $handle = fopen($key.".html","w"); fwrite($handle, $str); fclose($handle); echo("生成成功"); } ?>
The above is the detailed content of How to modify html files in php. For more information, please follow other related articles on the PHP Chinese website!