Page 1 of 1

Replace HTML with PHP

Posted: Tue Feb 22, 2011 5:00 pm
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.

Re: Replace HTML with PHP

Posted: Wed Feb 23, 2011 1:52 pm
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.

Re: Replace HTML with PHP

Posted: Wed Feb 23, 2011 1:59 pm
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');