You are here

public static function XmlHelper::parseElement in Helper 7

1 call to XmlHelper::parseElement()
XmlHelper::parseElements in lib/XmlHelper.php
Convert a string of XML to an associative array.

File

lib/XmlHelper.php, line 33

Class

XmlHelper

Code

public static function parseElement(SimpleXMLElement $element, array $options = array()) {
  $options += array(
    'simplify' => TRUE,
    'namespaces' => $element
      ->getNamespaces(TRUE),
  );
  $result = array();
  $result['key'] = $element
    ->getName();
  if (!empty($options['prefix'])) {
    $result['key'] = $options['prefix'] . ':' . $result['key'];
  }
  foreach ($element
    ->attributes() as $attribute_key => $attribute_value) {
    $result['attributes'][$attribute_key] = (string) $attribute_value;
  }
  if (!empty($options['namespaces'])) {
    foreach (array_keys($options['namespaces']) as $namespace) {
      foreach ($element
        ->attributes($namespace, TRUE) as $attribute_key => $attribute_value) {
        $result['attributes'][$namespace . ':' . $attribute_key] = (string) $attribute_value;
      }
    }
  }
  $children = array();
  foreach ($element
    ->children() as $child) {
    $children[] = static::parseElement($child, $options);
  }
  if (!empty($options['namespaces'])) {
    foreach (array_keys($options['namespaces']) as $namespace) {
      foreach ($element
        ->children($namespace, TRUE) as $child) {
        $children[] = static::parseElement($child, array(
          'prefix' => $namespace,
        ) + $options);
      }
    }
  }
  if (!empty($children)) {
    if (!empty($options['simplify'])) {
      static::simplifyElements($children);
    }
    $result['value'] = $children;
  }
  else {
    $result['value'] = (string) $element;
    if (!empty($options['simplify'])) {
      $result['value'] = trim($result['value']);
    }
  }
  return $result;
}