Skip to content

Instantly share code, notes, and snippets.

@mcfog
Created August 18, 2014 12:35
Show Gist options
  • Select an option

  • Save mcfog/f3b256824bb7c540c0a5 to your computer and use it in GitHub Desktop.

Select an option

Save mcfog/f3b256824bb7c540c0a5 to your computer and use it in GitHub Desktop.

Revisions

  1. mcfog created this gist Aug 18, 2014.
    71 changes: 71 additions & 0 deletions NotSimpleXMLElement.php
    Original 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;
    }
    }