Hi,

I'm self taught but I've got a pretty good grasp on php now.

What I want to do is completely separate it from my html....if that's possible. I keep reading about it but everyone keeps referring back to using templates which I don't want to do (unless they're my own).

So, as an example, on my home page (which I would like to have remain an html doc) I want to fill a div container with either a login/register script or (if the user is logged in) an ad.

Is there someway of identifying the div container so that an external php file is called and fills it? Or do I need to use php code in the div container to call the external php file?

I hope I have worded this clearly.

Thanks in advance.

Hi,

When I want to entirely separate my PHP and HTML content, I tend to use placeholders in my HTML code, and replace these using PHP.

A highly simplified example would be:

<!-- this file might be called index.html or index.tpl, etc
<html>
    <head>
        <title>{title}</title>
    </head>
</html>

Then, in the PHP you would use something like:

$strTemplate = '/path/to/index.tpl';

if(file_exists($strTemplate) && is_readable($strTemplate)) {
    $strTemplateContent = file_get_contents($strTemplate);
    
    // Populate an array with your tags and replacement content
    $arrTags = array(
        'title' => 'This is my title',
    );

    // Iterate through tags and replace with content
    foreach($arrTags as $strTag => $strContent) {
        $strTemplateContent = str_replace('{' . $strTag . '}', $strContent, $strTemplateContent);
    }

    // Remove any unreplaced tags - just so you don't have to specify content, or blank strings for every tag all the time
    $strTemplateContent = preg_replace('/{[^}]*}/', '', $strTemplateContent);

    // Do whatever you want with your content - e.g output it
    echo $strTemplateContent;

} else {
    $strTemplateFile = basename($strTemplate);
    throw new Exception("Template '$strTemplateFile' could not be found or is not readable.");
}

To get an include and essentially catch the content of an external file, the output control functions are useful.

There is probably a much better way of doing this. I've tried Smarty, and Zend View as well. Having logic in your templates isn't great, but can save a lot of time and headaches, especially with repeating content.

R.

Excellent thank you. I think I get it, I shall try it out and find out.

Thanks for sharing

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.