SimpleXML:将一棵树附加到另一棵树

The*_*nen 11 php simplexml

我有两个XML树,并希望将一棵树作为叶子添加到另一棵树.

显然:

$tree2->addChild('leaf', $tree1);
Run Code Online (Sandbox Code Playgroud)

不起作用,因为它只复制第一个根节点.

好吧,那么我想我会遍历整个第一棵树,将每个元素逐个添加到第二棵树.

但是考虑这样的XML:

<root>
  aaa
  <bbb/>
  ccc
</root>
Run Code Online (Sandbox Code Playgroud)

我如何访问"ccc"?tree1->children()只返回"bbb"....

sal*_*the 26

您已经看到,无法直接使用SimpleXML添加"树".但是,您可以使用一些DOM方法为您完成繁重的工作,同时仍在使用相同的基础XML.

$xmldict = new SimpleXMLElement('<dictionary><a/><b/><c/></dictionary>');
$kitty   = new SimpleXMLElement('<cat><sound>meow</sound><texture>fuzzy</texture></cat>');

// Create new DOMElements from the two SimpleXMLElements
$domdict = dom_import_simplexml($xmldict->c);
$domcat  = dom_import_simplexml($kitty);

// Import the <cat> into the dictionary document
$domcat  = $domdict->ownerDocument->importNode($domcat, TRUE);

// Append the <cat> to <c> in the dictionary
$domdict->appendChild($domcat);

// We can still use SimpleXML! (meow)
echo $xmldict->c->cat->sound;
Run Code Online (Sandbox Code Playgroud)


小智 11

您可以将此类用于接受子附加的SimpleXML对象

<?php

class MySimpleXMLElement extends SimpleXMLElement
{
    /**
     * Add SimpleXMLElement code into a SimpleXMLElement
     *
     * @param MySimpleXMLElement $append
     */
    public function appendXML($append)
    {
        if ($append) {
            if (strlen(trim((string)$append)) == 0) {
                $xml = $this->addChild($append->getName());
            } else {
                $xml = $this->addChild($append->getName(), (string)$append);
            }

            foreach ($append->children() as $child) {
                $xml->appendXML($child);
            }

            foreach ($append->attributes() as $n => $v) {
                $xml->addAttribute($n, $v);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Lin*_*ine 8

这是PHP手册页评论的好方法(仅使用SimpleXML,而不是DOM):

function append_simplexml(&$simplexml_to, &$simplexml_from)
{
    foreach ($simplexml_from->children() as $simplexml_child)
    {
        $simplexml_temp = $simplexml_to->addChild($simplexml_child->getName(), (string) $simplexml_child);
        foreach ($simplexml_child->attributes() as $attr_key => $attr_value)
        {
            $simplexml_temp->addAttribute($attr_key, $attr_value);
        }

        append_simplexml($simplexml_temp, $simplexml_child);
    }
} 
Run Code Online (Sandbox Code Playgroud)

还有使用样本.