给出两个SimpleXMLElement
对象,它们的结构如下(相同):
$ obj1
object SimpleXMLElement {
["@attributes"] =>
array(0) {
}
["event"] =>
array(1) {
[0] =>
object(SimpleXMLElement) {
["@attributes"] =>
array(1) {
["url"] =>
string "example.com"
}
}
}
}
$ obj2
object SimpleXMLElement {
["@attributes"] =>
array(0) {
}
["event"] =>
array(1) {
[0] =>
object(SimpleXMLElement) {
["@attributes"] =>
array(1) {
["url"] =>
string "another-example.com"
}
}
}
}
我正尝试将所有子event
项从第二个对象复制到第一个对象:
foreach ($obj2->event as $event) {
$obj1->event[] = $event
}
它们移动了,但是复制的对象现在为空。
$ obj1
object SimpleXMLElement {
["@attributes"] =>
array(0) {
}
["event"] =>
array(2) {
[0] =>
object(SimpleXMLElement) {
["@attributes"] =>
array(1) {
["url"] =>
string "example.com"
}
}
[1] =>
object(SimpleXMLElement) {
}
}
}
答案 0 :(得分:1)
SimpleXML的编辑功能相当有限,在这种情况下,您正在执行的分配和->addChild
都只能设置新元素的文本内容,而不能设置其属性和子元素。
在一种情况下,您需要更复杂的DOM API的强大功能。幸运的是,您可以使用dom_import_simplexml
和simplexml_import_dom
切换到另一个包装器,而在PHP中将两者混合在一起几乎没有任何代价。
一旦有了DOM表示形式,就可以使用the appendChild
method of DOMNode
添加一个完整的节点,但是有一个陷阱-您只能添加同一文档“拥有”的节点。因此,您必须首先在要编辑的文档上调用the importNode
method。
将所有内容放在一起,您将得到如下内容:
// Set up the objects you're copying from and to
// These don't need to be complete documents, they could be any element
$obj1 = simplexml_load_string('<foo><event url="example.com" /></foo>');
$obj2 = simplexml_load_string('<foo><event url="another.example.com" /></foo>');
// Get a DOM representation of the root element we want to add things to
// Note that $obj1_dom will always be a DOMElement not a DOMDocument,
// because SimpleXML has no "document" object
$obj1_dom = dom_import_simplexml($obj1);
// Loop over the SimpleXML version of the source elements
foreach ($obj2->event as $event) {
// Get the DOM representation of the element we want to copy
$event_dom = dom_import_simplexml($event);
// Copy the element into the "owner document" of our target node
$event_dom_copy = $obj1_dom->ownerDocument->importNode($event_dom, true);
// Add the node as a new child
$obj1_dom->appendChild($event_dom_adopted);
}
// Check that we have the right output, not trusting var_dump or print_r
// Note that we don't need to convert back to SimpleXML
// - $obj1 and $obj1_dom refer to the same data internally
echo $obj1->asXML();