Question

I'm building a CMS and as part of that any static HTML is being split up into reusable blocks and then saved in one central location. When we need each block we can add it to the string containing the page's HTML code using file_get_contents.

Being CMS some sections of the HTML need to have data loaded from the database. Now I could simply place holders, such as %cmsarea0%, %cmsarea1%, %cmsarea2% and so on, then use str_replace to put the HTML from the database in. However this doesn't seem like the best approach to me.

Ideally I would have several pre-defined variables in my page class, then in the HTML file have PHP to echo that variable out as it's loaded with file_get_contents, however no amount of testing seems to work. My PHP code in the .html file being loaded just gets commented out.

I know this sort of thing is possible as PHPBB use a similar thing, where they wrap their variables in braces and then it's parsed in somehow. But how do I achieve this?

Was it helpful?

Solution

I don't see why you wouldn't want to use str_replace(), this seems like the perfect remedy for me.

Try the following

HTML - myURL.php

<html>
    <body>
        <div id="myDiv1">%cmsarea1%</div>
        <div id="myDiv2">%cmsarea2%</div>
        <div id="myDiv3">%cmsarea3%</div>
    </body>
</html>

PHP - HTMLparse.php

$theContent = file_get_contents("myURL.php");

$var1 = $theContent.str_replace("%cmsarea1%", "My first variable");
$var2 = $theContent.str_replace("%cmsarea2%", "My second variable");
$var3 = $theContent.str_replace("%cmsarea3%", "My third variable");

OTHER TIPS

You got it all wrong. The HTML files should not be added using file_get_contents in PHP, but with include. This way, any PHP code within the HTML page will be executed (provided it is wrapped in tags). Remember that HTML "parts" which are included should have .php extension in order to execute the PHP script contained within. This is the basics of PHP-HTML templating.

Search the web for "php template website" and learn. This is the first result I got, and is pretty usable: http://www.1stwebdesigner.com/css/how-to-create-php-website-template/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top