note 83470 added to function.simplexml-element-asXML
| From: | mjijackson at gmail dot com | Date: | Tue, 27 May 2008 16:04:40 +0000 |
| Subject: | note 83470 added to function.simplexml-element-asXML | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-139863@lists.php.net to get a copy of this message | ||
A small improvement on Gary Malcolm's original asPrettyXML() method:
<?php
class XMLElement extends SimpleXMLElement
{
/**
* Outputs this element as pretty XML to increase readability.
*
* @param int $level (optional) The number of spaces to use for
* indentation, defaults to 4
* @return string The XML output
* @access public
*/
public function asPrettyXML($level = 4)
{
// get an array containing each XML element
$xml = explode("\n", preg_replace('/>\s*</',
">\n<", $this->asXML()));
// hold current indentation level
$indent = 0;
// hold the XML segments
$pretty = array();
// shift off opening XML tag if present
if (count($xml) && preg_match('/^<\?\s*xml/', $xml[0])) {
$pretty[] = array_shift($xml);
}
foreach ($xml as $el) {
if (preg_match('/^<([\w])+[^>\/]*>$/U', $el)) {
// opening tag, increase indent
$pretty[] = str_repeat(' ', $indent) . $el;
$indent += $level;
} else {
if (preg_match('/^<\/.+>$/', $el)) {
// closing tag, decrease indent
$indent -= $level;
}
$pretty[] = str_repeat(' ', $indent) . $el;
}
}
return implode("\n", $pretty);
}
}
?>
This method will make sure there is an opening XML tag before automatically shifting the first
element off the array, thus preserving the correct indentation level when printing child elements
instead of entire documents from the root node. It also allows you to pass the indentation level in
as a parameter instead of setting the class variable.
----
Server IP: 208.69.120.35
Probable Submitter: 64.0.193.254
----
Manual Page -- http://www.php.net/manual/en/function.simplexml-element-asXML.php
Edit -- https://master.php.net/note/edit/83470
Del: integrated -- https://master.php.net/note/delete/83470/integrated
Del: useless -- https://master.php.net/note/delete/83470/useless
Del: bad code -- https://master.php.net/note/delete/83470/bad+code
Del: spam -- https://master.php.net/note/delete/83470/spam
Del: non-english -- https://master.php.net/note/delete/83470/non-english
Del: in docs -- https://master.php.net/note/delete/83470/in+docs
Del: other reasons-- https://master.php.net/note/delete/83470
Reject -- https://master.php.net/note/reject/83470
Search -- https://master.php.net/manage/user-notes.php