note 83470 deleted from function.simplexml-element-asXML by danbrown

From: Date: Wed, 16 Sep 2009 15:43:23 +0000
Subject: note 83470 deleted from function.simplexml-element-asXML by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-160655@lists.php.net to get a copy of this message
Note Submitter: mjijackson at gmail dot com ---- 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.

« previous php.notes (#160655) next »