Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOMDocument::saveHTML($domnode) in PHP 5.2?

Tags:

dom

php

I have several functions in a class that return saveHTML(). After I echo more than one function in the class saveHTML(), it repeats some of the HTML. I initially solved this by doing saveHTML($node) but that doesn't seem to be an option now.

I didn't know saveHTML($domnode) was only available in PHP 5.3.6 and I have no control over the server I uploaded the files to so now I have to make it compatible with PHP 5.2.

For simplicity's sake it and only to show my problem it looks similar to this:

<?php

class HTML
{
    private $dom;

    function __construct($dom)
    {
        $this->dom = $dom;
    }

    public function create_paragraph()
    {
        $p = $this->dom->createElement('p','Text 1.');

            $this->dom->appendChild($p);

        return $this->dom->saveHTML();
    }

    public function create_paragraph2()
    {
        $p = $this->dom->createElement('p','Text 2.');

            $this->dom->appendChild($p);

        return $this->dom->saveHTML();
    }
}

$dom = new DOMDocument;
$html = new HTML($dom);

?>
<html>
<body>
<?php

echo $html->create_paragraph();

echo $html->create_paragraph2();

?>
</body>
</html>

Outputs:

<html>
<body>
<p>Text 1.</p>
<p>Text 1.</p><p>Text 2.</p>
</body>

I have an idea why it's happening but I have no idea how to not make it repeat without saveHTML($domnode). How can I make it work properly with PHP 5.2?

Here's an example of what I want to be able to do:

http://codepad.viper-7.com/o61DdJ

like image 475
Tek Avatar asked Jun 04 '11 14:06

Tek


1 Answers

What I do, is just save the node as XML. There are a few differences in the syntax, but it's good enough for most uses:

return $dom->saveXml($node);
like image 112
ircmaxell Avatar answered Sep 28 '22 00:09

ircmaxell