02 Sep 2010

PHP domNode toString XML

Blog, Code, PHP 3 Comments

This is a very simple task I needed to do which basically consisted of getting a domNode as a string and printing the content. This may not be very useful in an application but it may be very useful for debugging purposes.

On the PHP documentation pages I found some code which is totally unnecessary for this task which basically loops over and over the content and places a ‘ < ' and a ' > ‘ before and after each child element and prints out the content using get_content(), node_name() and attributes.

My simpler solution was to create a new temporary document, import the node and use the document’s methods to get the content as a string. Simple hah :D !

My simpler solution:

$temp_doc = new DOMDocument('1.0', 'UTF-8');
$temp_node = $temp_doc->importNode($myDomNode, TRUE);
$temp_doc->appendChild($temp_node);
$my_node_as_string = $temp_doc->saveHTML();
Solution on PHP Documentation:

function GetContentAsString($node) {
  $st = "";
  foreach ($node->child_nodes() as $cnode)
   if ($cnode->node_type()==XML_TEXT_NODE)
     $st .= $cnode->node_value();
   else if ($cnode->node_type()==XML_ELEMENT_NODE) {
     $st .= "<" . $cnode->node_name();
     if ($attribnodes=$cnode->attributes()) {
       $st .= " ";
       foreach ($attribnodes as $anode)
         $st .= $anode->node_name() . "='" .
           $anode->node_value() . "'";
       }
     $nodeText = GetContentAsString($cnode);
     if (empty($nodeText) && !$attribnodes)
       $st .= " />";        // unary
     else
       $st .= ">" . $nodeText . "node_name() . ">";
     }
  return $st;
  }

3 Responses to “PHP domNode toString XML”

  1. Jack Nolan says:

    Found your site today through 123 Search. Awesome blog you’ve got, bookmarked.

  2. White says:

    $node->ownerDocument->saveXML($node); is actually yet easier, shorter and way more resource friendly, because you wont copy the whole document into another one.

  3. dan says:

    Should note this is only PHP >= 5.3.6, below which the solution on the php man is still useful

Leave a Reply