28 Jul

innerHTML in php-dom

DOM does not officially have an innerHTML parameter, but it’s incredibly useful. I found a need for something similar when working on some DOM stuff, so had to write a version.

function string_getInsertedString($long_string,$short_string,$is_html=false){
  if($short_string>=strlen($long_string))return false;
  $insertion_length=strlen($long_string)-strlen($short_string);
  for($i=0;$i<strlen($short_string);++$i){
    if($long_string[$i]!=$short_string[$i])break;
  }
  $inserted_string=substr($long_string,$i,$insertion_length);
  if($is_html && $inserted_string[$insertion_length-1]=='<'){
    $inserted_string='<'.substr($inserted_string,0,$insertion_length-1);
  }
  return $inserted_string;
}
function DOMElement_getOuterHTML($document,$element){
  $html=$document->saveHTML();
  $element->parentNode->removeChild($element);
  $html2=$document->saveHTML();
  return string_getInsertedString($html,$html2,true);
}

Okay, this is outerHTML, not inner, but if you want the innerHTML, then just do something like this:

$innerHTML=preg_replace('/^<[^>]*>(.*)<[^>]*>$/','\1',DOMElement_getOuterHTML($document,$element));

There is possibly a better way of doing this, but the above worked for me in the “throwaway” code I was writing.

7 thoughts on “innerHTML in php-dom

  1. Pingback: Kae Verans’ Blog: innerHTML in php-dom | Development Blog With Code Updates : Developercast.com

  2. Hello!

    This is a wonderful script, good work! It really saved my day.
    Thank you so much! Hope its okey to use it as part in a little cms
    system where building?

    In any way, please send me a mail telling its okey.
    Otherwise I will remove it.

    Thanks!

    Best regards
    Adrian

  3. Hi Guys,

    There is an easy and clean way of doing it using DOMDocument class itself.

    See the example below.

    function convertNodeToDOM($domNode) {

    //this function receives a node and converts it to Dom document

    $doc = new DOMDocument();

    $doc->appendChild($doc->importNode($domNode,true));

    return $doc;

    }

    $tmpDOM = convertNodeToDOM($tmpDiv); //tmp div can be retrieves using getElementById etc

    $innerHTML = saveHTML($tmpDOM);

    Regards,
    Lokesh

  4. Expanding on Lokesh’s solution…

    To get the innerHTML of a specific element ($elem_id) in a specific html file ($filepath), you have to accommodate multiple children in that element:

    $innerHTML = ”;
    $doc = new DOMDocument();
    $doc->loadHTMLFile($filepath);
    $elem = $doc->getElementById($elem_id);

    // loop through all childNodes, getting html
    $children = $elem->childNodes;
    foreach ($children as $child) {
    $tmp_doc = new DOMDocument();
    $tmp_doc->appendChild($tmp_doc->importNode($child,true));
    $innerHTML .= $tmp_doc->saveHTML();
    }

  5. Pingback: ??????? » [Web] ????

Comments are closed.