Created
August 18, 2014 12:35
-
-
Save mcfog/f3b256824bb7c540c0a5 to your computer and use it in GitHub Desktop.
Revisions
-
mcfog created this gist
Aug 18, 2014 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,71 @@ <?php class NotSimpleXMLElement extends SimpleXMLElement { const ATTR = 'attr'; const NAME = 'name'; const CHILDREN = 'children'; const VALUE = 'value'; public static function fromArray(array $arr) { $root = new static(sprintf('<%1$s>%2$s</%1$s>', $arr[self::NAME], $arr[self::VALUE])); self::importArr($root, $arr); return $root; } /** * @param $root * @param array $arr */ protected static function importArr(self $root, array $arr) { if (isset($arr[self::ATTR])) { foreach ($arr[self::ATTR] as $k => $v) { $root->addAttribute($k, $v); } } if (isset($arr[self::CHILDREN])) { foreach ($arr[self::CHILDREN] as $k => $v) { self::importArr($root->addChild($v[self::NAME], $v[self::VALUE]), $v); } } } public function toArray() { $result = [ self::NAME => $this->getName(), ]; $attr = $this->attributes(); if ($attr->count() > 0) { $result[self::ATTR] = []; foreach ($attr as $k => $v) { $result[self::ATTR][$k] = (string)$v; } } $children = $this->children(); if ($children->count() > 0) { $result[self::CHILDREN] = []; foreach ($children as $k => $v) { /** * @var self $v */ $result[self::CHILDREN][] = $v->toArray(); } } $result[self::VALUE] = (string)$this; return $result; } }