note 77816 modified in function.simplexml-element-asXML by danbrown

From: Date: Wed, 16 Sep 2009 15:42:40 +0000
Subject: note 77816 modified in function.simplexml-element-asXML by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-160652@lists.php.net to get a copy of this message
I extended SimpleXml and added this code to give me pleasant source code XML. <?php public function asPrettyXML() { $string = $this->asXML(); /** * put each element on it's own line */ $string =preg_replace("/>\s*</",">\n<",$string); /** * each element to own array */ $xmlArray = explode("\n",$string); /** * holds indentation */ $currIndent = 0; /** * set xml element first by shifting of initial element */ $string = array_shift($xmlArray) . "\n"; foreach($xmlArray as $element) { /** find open only tags... add name to stack, and print to string * increment currIndent */ if (preg_match('/^<([\w])+[^>\/]*>$/U',$element)) { $string .= str_repeat(' ', $currIndent) . $element . "\n"; $currIndent += self::indent; } /** * find standalone closures, decrement currindent, print to string */ elseif ( preg_match('/^<\/.+>$/',$element)) { $currIndent -= self::indent; $string .= str_repeat(' ', $currIndent) . $element . "\n"; } /** * find open/closed tags on the same line print to string */ else { $string .= str_repeat(' ', $currIndent) . $element . "\n"; } } return $string; } ?> Regards, Gary Malcolm --was-- I extended SimpleXml and added this code to give me pleasant source code XML. I'm sure it's ugly so if you can do it better go ahead... <?php public function asPrettyXML() { $string = $this->asXML(); /** * put each element on it's own line */ $string =preg_replace("/>\s*</",">\n<",$string); /** * each element to own array */ $xmlArray = explode("\n",$string); /** * holds indentation */ $currIndent = 0; /** * set xml element first by shifting of initial element */ $string = array_shift($xmlArray) . "\n"; foreach($xmlArray as $element) { /** find open only tags... add name to stack, and print to string * increment currIndent */ if (preg_match('/^<([\w])+[^>\/]*>$/U',$element)) { $string .= str_repeat(' ', $currIndent) . $element . "\n"; $currIndent += self::indent; } /** * find standalone closures, decrement currindent, print to string */ elseif ( preg_match('/^<\/.+>$/',$element)) { $currIndent -= self::indent; $string .= str_repeat(' ', $currIndent) . $element . "\n"; } /** * find open/closed tags on the same line print to string */ else { $string .= str_repeat(' ', $currIndent) . $element . "\n"; } } return $string; } ?> Regards, Gary Malcolm http://php.net/manual/en/function.simplexml-element-asXML.php

« previous php.notes (#160652) next »