I'm not sure the best way to explain this. I don't know very much about PHP but am starting to learn, and I'm curious about how a company I used to work for ran their sites. If I started with a basic template like
<html>
<body>
<div id="header"></div>
<div id="content">
%content%
</div>
<div id="footer"></div>
</body>
</html>
I could call that file template.php - then when I created index.php, all I had to put in was a php required file at the top of the page, and then code like this:
<h1>Welcome</h1>
<p>text here</p>
then when you went to index.php, it would show the template design and "%content%" would automatically be replaced with the content from index.php
I've been looking for a solution like this for creating my own websites. I know I can just put include code on each page to include the header, then include the footer, etc - but I like this cleaner way of doing it and would like to learn how it worked.
Replace HTML with PHP
Moderator: General Moderators
Re: Replace HTML with PHP
Using ob_start() and ob_get_clean() is usually key to a templating system. Consider:
Then instead of %content% you would do `<?php echo $bodyContent?>`. Or if you like the %content% idea, just do `echo str_replace('%content%', $bodyContent, file_get_contents('headerFooter.php'));` I just like to have my header/footer file be PHP so I can do some basic logic in there.
Code: Select all
ob_start();
include('index.php');
$bodyContent = ob_get_clean();
include('headerFooter.php');- AbraCadaver
- DevNet Master
- Posts: 2572
- Joined: Mon Feb 24, 2003 10:12 am
- Location: The Republic of Texas
- Contact:
Re: Replace HTML with PHP
For this simple need I would just echo in the template:
Code: Select all
<html>
<body>
<div id="header"></div>
<div id="content">
<?php echo $content; ?>
</div>
<div id="footer"></div>
</body>
</html>Code: Select all
$content = 'something';
inlude('template.php');mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.