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;
  if($is_html && $inserted_string[$insertion_length-1]=='<'){
  return $inserted_string;
function DOMElement_getOuterHTML($document,$element){
  return string_getInsertedString($html,$html2,true);

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


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.


    Best regards

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


    return $doc;


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

    $innerHTML = saveHTML($tmpDOM);


  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();
    $elem = $doc->getElementById($elem_id);

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

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

Comments are closed.