Home  >  Article  >  Backend Development  >  PHP implements simple code separation template engine

PHP implements simple code separation template engine

黄舟
黄舟Original
2016-12-21 10:16:101047browse

Use the Replace function, that is, the str_replace function of PHP, to replace the keywords in the content read in the template file with the content in the variable, thereby achieving simple template separation.
Template file template.htm:



%title%


%title %




%body%



php file:

//The Replace function is used to replace the keywords in the content read from the template file with the content in the variable
function Replace($row)
{
//Define the variable used for replacement
$title = "Article title ";
$body = "Here is the body of the article";
//Replace the keywords in the parameters
$row = str_replace("%title%", $title, $row);
$row = str_replace("%body %", $body, $row);
//Return the replaced result
return $row;
}
//Template file pointer
$f_tem = fopen("template.htm","r");
/ /Generated file pointer
$f_new = fopen("new.htm","w");
//Loop through the template file, reading one line at a time
while(!feof($f_tem))
{
$ row = fgets($f_tem);
$row = Replace($row); //Replace the keywords in the read content
fwrite($f_new, $row); //Write the replaced content into the generated HTML File
}
//Close the file pointer
fclose($f_new);
fclose($f_tem);
?>


Generate a new html page: new.html


Article title


Article title




Here is the body of the article 


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