note 108688 modified in book.simplexml by danbrown
| From: | danbrown@php.net | Date: | Thu, 17 May 2012 19:03:11 +0000 |
| Subject: | note 108688 modified in book.simplexml by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-188043@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. <?php 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 	
); 	} ?>
--was--
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
);
}
http://php.net/manual/en/book.simplexml.php