You may need to save all or part of a DOMDocument as an XHTML-friendly string, something compliant with both XML and HTML 4. Here's the DOMDocument class extended with a saveXHTML method:
<?php
class XHTMLDocument extends DOMDocument {
public $selfTerminate = array(
'area','base','basefont','br','col','frame','hr','img','input','link','meta','param'
);
public function saveXHTML(DOMNode $node=null) {
if (!$node) $node = $this->firstChild;
$doc = new DOMDocument('1.0');
$clone = $doc->importNode($node->cloneNode(false), true);
$term = in_array(strtolower($clone->nodeName), $this->selfTerminate);
$inner='';
if (!$term) {
$clone->appendChild(new DOMText(''));
if ($node->childNodes) foreach ($node->childNodes as $child) {
$inner .= $this->saveXHTML($child);
}
}
$doc->appendChild($clone);
$out = $doc->saveXML($clone);
return $term ? substr($out, 0, -2) . ' />' : str_replace('><', ">$inner<", $out);
}
}
?>
This hasn't been benchmarked, but is probably significantly slower than saveXML or saveHTML and should be used sparingly.