note 104218 added to class.domdocument
| From: | NickM at osu1 dot php dot net | Date: | Wed, 01 Jun 2011 17:16:09 +0000 |
| Subject: | note 104218 added to class.domdocument | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-180168@lists.php.net to get a copy of this message | ||
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
/**
* XHTML Document
*
* Represents an entire XHTML DOM document; serves as the root of the document tree.
*/
class XHTMLDocument extends DOMDocument {
/**
* These tags must always self-terminate. Anything else must never self-terminate.
*
* @var array
*/
public $selfTerminate = array(
'area','base','basefont','br','col','frame','hr','img','input','link','meta','param'
);
/**
* saveXHTML
*
* Dumps the internal XML tree back into an XHTML-friendly string.
*
* @param DOMNode $node
* Use this parameter to output only a specific node rather than the entire document.
*/
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.
----
Server IP: 69.147.83.197
Probable Submitter: 71.229.5.91
----
Manual Page -- http://www.php.net/manual/en/class.domdocument.php
Edit -- https://master.php.net/note/edit/104218
Del: integrated -- https://master.php.net/note/delete/104218/integrated
Del: useless -- https://master.php.net/note/delete/104218/useless
Del: bad code -- https://master.php.net/note/delete/104218/bad+code
Del: spam -- https://master.php.net/note/delete/104218/spam
Del: non-english -- https://master.php.net/note/delete/104218/non-english
Del: in docs -- https://master.php.net/note/delete/104218/in+docs
Del: other reasons-- https://master.php.net/note/delete/104218
Reject -- https://master.php.net/note/reject/104218
Search -- https://master.php.net/manage/user-notes.php