note 108688 added to book.simplexml
| From: | xaviered at gmail dot com | Date: | Thu, 17 May 2012 19:00:21 +0000 |
| Subject: | note 108688 added to book.simplexml | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-188042@lists.php.net to get a copy of this message | ||
Here is a recursive function that will convert a given SimpleXMLElement object into an array,
preserving namespaces and attributes.
function xmlObjToArr($obj) {
$namespace = $obj->getDocNamespaces(true);
$namespace[NULL] = NULL;
$children = array();
$attributes = array();
$name = strtolower((string)$obj->getName());
$text = trim((string)$obj);
if( strlen($text) <= 0 ) {
$text = NULL;
}
// get info for all namespaces
if(is_object($obj)) {
foreach( $namespace as $ns=>$nsUrl ) {
// atributes
$objAttributes = $obj->attributes($ns, true);
foreach( $objAttributes as $attributeName => $attributeValue ) {
$attribName = strtolower(trim((string)$attributeName));
$attribVal = trim((string)$attributeValue);
if (!empty($ns)) {
$attribName = $ns . ':' . $attribName;
}
$attributes[$attribName] = $attribVal;
}
// children
$objChildren = $obj->children($ns, true);
foreach( $objChildren as $childName=>$child ) {
$childName = strtolower((string)$childName);
if( !empty($ns) ) {
$childName = $ns.':'.$childName;
}
$children[$childName][] = xmlObjToArr($child);
}
}
}
return array(
'name'=>$name,
'text'=>$text,
'attributes'=>$attributes,
'children'=>$children
);
}
----
Server IP: 208.69.120.55
Probable Submitter: 199.106.173.115
----
Manual Page -- http://www.php.net/manual/en/book.simplexml.php
Edit -- https://master.php.net/note/edit/108688
Del: integrated -- https://master.php.net/note/delete/108688/integrated
Del: useless -- https://master.php.net/note/delete/108688/useless
Del: bad code -- https://master.php.net/note/delete/108688/bad+code
Del: spam -- https://master.php.net/note/delete/108688/spam
Del: non-english -- https://master.php.net/note/delete/108688/non-english
Del: in docs -- https://master.php.net/note/delete/108688/in+docs
Del: other reasons-- https://master.php.net/note/delete/108688
Reject -- https://master.php.net/note/reject/108688
Search -- https://master.php.net/manage/user-notes.php