Created
August 18, 2014 12:35
-
-
Save mcfog/f3b256824bb7c540c0a5 to your computer and use it in GitHub Desktop.
带array正反转换的XMLElement
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 | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment