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

4 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
  3. Thank you so much for the outerHTML function. wish it were cleaner, and did not need a temporary DOM object. But it's not your fault, I am just happy to be able to have a function to call, without having to dork around with it myself. An "outerHtml" property SHOULD have been included in the DOM. I thank you for your contribution. -Don! Briggs

    ReplyDelete