note 85117 deleted from function.simplexml-element-asXML by danbrown
| From: | danbrown@php.net | Date: | Wed, 16 Sep 2009 15:43:34 +0000 |
| Subject: | note 85117 deleted from function.simplexml-element-asXML by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-160656@lists.php.net to get a copy of this message | ||
Note Submitter: arian.stolwijk [at] gmail [dot] com
----
Another little improvement on Gary Malcolm's original asPrettyXML() and mjijackson's
version:
<?php
class Awf_Xml extends SimpleXMLElement {
public function asXml($file=null,$level=4){
// get an array containing each XML element
$xml = explode("\n", preg_replace('/>\s*</',
">\n<", parent::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) {
$line = str_replace(' ','',trim($el));
if(empty($line)){
// There is nothing on this line, so we can skip it;)
continue;
}
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;
}elseif(preg_match('/^<([\w])+[^>\/]*>.*<\/.+>$/',$el)){
// Open and close on the same line
$pretty[] = str_repeat(' ', $indent) . $el;
}else{
// There is no tag at this line, so we don't want to mess with it's
content!
$pretty[] = $el;
}
}
}
$xml = implode("\n", $pretty);
if(!empty($file)){
return (bool)file_put_contents($file,$xml);
}else{
return $xml;
}
}
}
?>