Advertisement
TehWan

PHP - XML to Array

Mar 7th, 2014
964
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.07 KB | None | 0 0
  1. <?php
  2. class XML
  3. {
  4.  
  5.     /**
  6.      * Converts an XML node to an array
  7.      *
  8.      * @param \SimpleXMLElement $node XML node
  9.      *
  10.      * @return array
  11.      *
  12.      * @note Does not handle namespaces
  13.      */
  14.     public static function toArray(\SimpleXMLElement $node)
  15.     {
  16.         $output = array();
  17.  
  18.         $attributes = array();
  19.         foreach ($node->attributes() as $key => $val) {
  20.             $attributes[$key] = (string)$val;
  21.         }
  22.  
  23.         $text = trim((string)$node);
  24.  
  25.         if (! empty($attributes)) {
  26.             $output['@attributes'] = $attributes;
  27.         }
  28.  
  29.         if (! empty($text)) {
  30.             $output['_'] = $text;
  31.         }
  32.  
  33.         $children = array();
  34.         foreach ($node->children() as $childName => $childNode) {
  35.             $children[$childName][] = self::toArray($childNode);
  36.         }
  37.  
  38.         foreach ($children as $childName => $childList) {
  39.             if (count($childList) === 1) {
  40.                 $output[$childName] = $childList[0];
  41.             } else {
  42.                 $output[$childName] = $childList;
  43.             }
  44.         }
  45.  
  46.         return $output;
  47.     }
  48.  
  49.     public static function toObject(\SimpleXMLElement $node)
  50.     {
  51.         $obj = new \stdClass();
  52.         self::toObject_R($obj, self::toArray($node));
  53.  
  54.         return $obj;
  55.     }
  56.  
  57.     private static function toObject_R($obj, $item)
  58.     {
  59.         if (! is_array($item)) {
  60.             return;
  61.         }
  62.  
  63.         foreach ($item as $key => $val) {
  64.             if (is_array($val)) {
  65.                 if (array_keys($val) === range(0, count($val) - 1)) {
  66.                     $q = array();
  67.                     foreach ($val as $i => $v) {
  68.                         $q[$i] = new \stdClass();
  69.                         self::toObject_R($q[$i], $v);
  70.                     }
  71.                     $obj->$key = $q;
  72.                 } else {
  73.                     $obj->$key = new \stdClass();
  74.                     self::toObject_R($obj->$key, $val);
  75.                 }
  76.             } else {
  77.                 $obj->$key = $val;
  78.             }
  79.         }
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement