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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – SimpleXML:将一棵树追加到另一棵树上脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个 XML树,并希望添加一个树作为另一个树叶.

显然:

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

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

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

但是请考虑这样的XML:

<root>
  aaa
  <bbb/>
  ccc
</root>

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

您不能直接使用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;

脚本宝典总结

以上是脚本宝典为你收集整理的php – SimpleXML:将一棵树追加到另一棵树上全部内容,希望文章能够帮你解决php – SimpleXML:将一棵树追加到另一棵树上所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。