PHP domNode toString XML
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
!
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 . "" .
$cnode->node_name() . ">";
}
return $st;
}


Found your site today through 123 Search. Awesome blog you’ve got, bookmarked.
$node->ownerDocument->saveXML($node); is actually yet easier, shorter and way more resource friendly, because you wont copy the whole document into another one.
Should note this is only PHP >= 5.3.6, below which the solution on the php man is still useful