Skip to content

Instantly share code, notes, and snippets.

@leihog
Created December 14, 2010 13:30
Show Gist options
  • Save leihog/740410 to your computer and use it in GitHub Desktop.
Save leihog/740410 to your computer and use it in GitHub Desktop.
Very basic class to convert simple xml snippets in to arrays.
<?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