Replace HTML with PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mollycampbell
Forum Newbie
Posts: 1
Joined: Tue Feb 22, 2011 4:54 pm

Replace HTML with PHP

Post by mollycampbell »

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.
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: Replace HTML with PHP

Post by tr0gd0rr »

Using ob_start() and ob_get_clean() is usually key to a templating system. Consider:

Code: Select all

ob_start();
include('index.php');
$bodyContent = ob_get_clean();
include('headerFooter.php');
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.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Replace HTML with PHP

Post by AbraCadaver »

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.
Post Reply