Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including template file in PHP and replacing variables

I have a .tpl file which contains the HTML code of my webpage and a .php file that I want to use the HTML code in it and replace some variables. For example imagine this is my file.tpl:

<html>
<head>
<title>{page_title}</title>
</head>
<body>
Welcome to {site_name}!
</body>
</html>

and I want to define {page_title} and {site_name} in my php file and display them.

One way we can do this is to load the page code in a variable and then replace {page_title} and {site_name} and then echo them.

But I don't know that it's the best way or not because I think there will be some problem if the .tpl file is large.

Please help me to find the best way. Thanks :-)

like image 884
Ahmad Ameri Avatar asked Dec 26 '22 15:12

Ahmad Ameri


1 Answers

One way you could do it:

$replace = array('{page_title}', '{site_name}');
$with = array('Title', 'My Website');

$contents = file_get_contents('my_template.tpl');

echo str_replace($replace, $with, $contents);

Update: removed include, used file_get_contents()

like image 98
Mihai Iorga Avatar answered Dec 28 '22 09:12

Mihai Iorga