note 85117 added to function.simplexml-element-asXML
| From: | arian.stolwijk | Date: | Fri, 15 Aug 2008 13:19:32 +0000 |
| Subject: | note 85117 added to function.simplexml-element-asXML | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-143523@lists.php.net to get a copy of this message | ||
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;
}
}
}
?>
----
Server IP: 83.137.20.135
Probable Submitter: 194.30.182.156
----
Manual Page -- http://www.php.net/manual/en/function.simplexml-element-asXML.php
Edit -- https://master.php.net/note/edit/85117
Del: integrated -- https://master.php.net/note/delete/85117/integrated
Del: useless -- https://master.php.net/note/delete/85117/useless
Del: bad code -- https://master.php.net/note/delete/85117/bad+code
Del: spam -- https://master.php.net/note/delete/85117/spam
Del: non-english -- https://master.php.net/note/delete/85117/non-english
Del: in docs -- https://master.php.net/note/delete/85117/in+docs
Del: other reasons-- https://master.php.net/note/delete/85117
Reject -- https://master.php.net/note/reject/85117
Search -- https://master.php.net/manage/user-notes.php