Sunday, November 22, 2009

DOMElement innerHMTL

Currently, there's no built-in method in the DOMElement that gets the inner/outerHTML of the element. There are a few solutions in the comments and on other blogs, but they loop through all the childNodes in order to get the innerHMTL. Getting the outerHTML is much easier (no looping) and just as useful: function outerHTML($e) { $doc = new DOMDocument(); $doc->appendChild($doc->importNode($e, true)); return $doc->saveHTML(); } Still, I'm not sure that is the most optimal way of doing it. It seems that DOMDocument::saveXML accepts an optional DOMElement parameter which, when specified, causes the function to return only that element's XML. You could rewrite our outerHTML function like this: function outerXML($e) { return $e->ownerDocument->saveXML($e); }

3 comments:

  1. Hello.

    Perhaps is Pygmentool (http://pygmentool.mine.nu/) off line?

    ReplyDelete
  2. Yes, I'm sorry, my server is acting up. It's back now.

    ReplyDelete