Is there a way to add a PHP SimpleXMLElement to another SimpleXMLElement?

微笑、不失礼 提交于 2019-12-28 04:28:33

问题


The "addChild" method of SimpleXMLElement seems like it should be the right choice, but it apparently only takes strings representing the tagname of the new child.

There's the object-ish notation for referencing nodes of the tree and setting them, e.g. $simpleXMLNode->child = value, but that only seems to work for simple text/numeric values. If I try the following:

$s = new SimpleXMLElement('<root/>');
$t = new SimpleXMLElement('<child/>');
$s->a = $t;
echo $s->asXML()

I get:

<?xml version="1.0"?>
<root><a></a></root>

when I was hoping for:

<?xml version="1.0"?>
<root><a><child/></a></root>

I thought of converting $t to a string and then adding it (after stripping out the XML declaration):

$s->a = substr($t->asXML(),22)

But this yields:

<?xml version="1.0"?>
<root><a>&lt;child/&gt;</a></root>

Again, not what I was hoping for.

Is there a typical way to accomplish this kind of thing with SimpleXML?


回答1:


Hey unknown. You have to use the DOMElement interface to your SimpleXML objects to achieve this.

<?php

$s = new SimpleXMLElement('<root/>');
$t = new DOMElement('child');

$dom = dom_import_simplexml($s);
$dom->appendChild($t);

echo $s->asXML();
// <root><child/></root>

If you need more specific details, let me know. There are several examples in the documentation and comments for the dom_import_simplexml() method too: http://php.net/dom_import_simplexml




回答2:


I'm not sure if this will help but you could also extend SimpleXML to work as you expect. Here is a project I worked on for bLibrary Xml class. You can look at it to tailor SimpleXml to work as you expect it.



来源:https://stackoverflow.com/questions/1157104/is-there-a-way-to-add-a-php-simplexmlelement-to-another-simplexmlelement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!