phphtmlparsingphp-parser

How do I parse variables in HTML during file_get_contents


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?


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");