DOMDocument and inline PHP

I’ve written a simple class which I’m hoping to use to generate cached versions of documents. Most of the content of these documents will be static, but there are a few cases where dynamic content will need to be included, and this will be done by injecting small PHP blocks into the document before the whole thing is returned. The idea is that each generated document will work pretty much as a standalone document.

Here is my code so far (with various parts removed for simplicity). It’s still pretty rough because I’ve not been working on it for long, but you should get the idea:

class TemplateParser {

    public function InsertIntoDiv(DOMDocument $dom, $div_id, $content) {

        if(in_array($div_id, $this->GetEditableDivs($dom))) {

            $div = $dom->getElementById($div_id);
            $div->nodeValue = PHP_EOL . "\	"; // remove current contents of div

            $f = $dom->createDocumentFragment();
            $div->appendChild($f); // insert new content into div



    public function OutputHTML(DOMDocument $dom) {
        return $dom->saveHTML();


And here is the code I’m using to inject the content:

$html = file_get_contents('template.html');

$dom = new DOMDocument;

$tpl = new TemplateParser();

$tpl->InsertIntoDiv($dom, 'header', '<?php echo "Hello World! This is dynamic content."; ?'.'>');
$tpl->InsertIntoDiv($dom, 'main', '<h1>Welcome to my website!</h1><p>This is static content.</p>');

echo htmlentities($tpl->OutputHTML($dom));

This works fine with one exception: the closing ?> tag in the PHP fragment I’m trying to insert is being changed, meaning the output is something like this:

<?php echo "Hello World! This is dynamic content."; >

As you can see the ? in the closing tag is being removed altogether. I’m assuming this is happening for a very good reason, but I’m wondering if there’s any way of avoiding it. I’m aware that it would be very easy (almost too easy) to do a final pass of the resulting code with preg_replace to put the closing PHP tags back in, but I figure there’s got to be a more elegant solution.

Any help or input would be much appreciated :slight_smile:


You could probably also use <script language=“php”>echo 5;</script>

Ah, that looks perfect. Will give that a go this evening and let you know how I get on. Thanks :slight_smile: