php – SimpleXML:将一棵树追加到另一棵树上

前端之家收集整理的这篇文章主要介绍了php – SimpleXML:将一棵树追加到另一棵树上前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个 XML树,并希望添加一个树作为另一个树叶.

显然:

  1. $tree2->addChild('leaf',$tree1);

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

好的,所以我以为我会遍历整个第一棵树,每一个元素逐个添加到第二个树.

但是请考虑这样的XML:

  1. <root>
  2. aaa
  3. <bbb/>
  4. ccc
  5. </root>

如何访问“ccc”? tree1> children()只返回“bbb”….

您不能直接使用SimpleXML添加“树”,如您所见.但是,您可以使用某些DOM方法为您提供同样的基础XML,同时也可以为您提供解决方案.
  1. $xmldict = new SimpleXMLElement('<dictionary><a/><b/><c/></dictionary>');
  2. $kitty = new SimpleXMLElement('<cat><sound>meow</sound><texture>fuzzy</texture></cat>');
  3.  
  4. // Create new DOMElements from the two SimpleXMLElements
  5. $domdict = dom_import_simplexml($xmldict->c);
  6. $domcat = dom_import_simplexml($kitty);
  7.  
  8. // Import the <cat> into the dictionary document
  9. $domcat = $domdict->ownerDocument->importNode($domcat,TRUE);
  10.  
  11. // Append the <cat> to <c> in the dictionary
  12. $domdict->appendChild($domcat);
  13.  
  14. // We can still use SimpleXML! (meow)
  15. echo $xmldict->c->cat->sound;

猜你在找的PHP相关文章