Created
December 14, 2010 13:30
-
-
Save leihog/740410 to your computer and use it in GitHub Desktop.
Very basic class to convert simple xml snippets in to arrays.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* (extremely) simple class to convert a DOMNode to an array. | |
* @todo Add support for attributes, namespaces and other goodies... | |
*/ | |
class XmlToArray | |
{ | |
/** | |
* Checks if node has any children other than just text | |
* | |
* @param DOMNode | |
* @return boolean | |
*/ | |
public static function nodeHasChild( $node ) | |
{ | |
if ( $node->hasChildNodes() ) | |
{ | |
foreach ( $node->childNodes as $child ) | |
{ | |
if ( $child->nodeType == XML_ELEMENT_NODE ) | |
{ | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
/** | |
* Takes a DOMNode (or a DOMNodeList) and returns it as an array | |
* | |
* @param DOMNode|DOMNodeList $item | |
* @return array | |
*/ | |
public static function process( $xml ) | |
{ | |
if ( $xml instanceOf DOMNodeList ) | |
{ | |
$items = array(); | |
foreach ( $xml as $item ) | |
{ | |
$items[] = self::toArray( $item ); | |
} | |
return $items; | |
} | |
$itemData = array(); | |
foreach ( $xml->childNodes as $node ) | |
{ | |
if ( self::nodeHasChild( $node ) ) | |
{ | |
$itemData[$node->nodeName] = self::process( $node ); | |
} | |
else | |
{ | |
$itemData[$node->nodeName] = $node->nodeValue; | |
} | |
} | |
return $itemData; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment