使用PHP插入XML结构作为另一个XML元素的子元素


Insert XML structure as a child of another XML Element using PHP

是否可以插入一个PHP SimpleXMLElement作为另一个元素的子元素

$xml   = new SimpleXMLElement('<root/>');
$xml_a = new SimpleXMLElement('<parent/>');
$xml_b = new SimpleXMLElement('<child/>');
$xml_b->addAttribute('attribute','value');
$xml_b->addChild('item','itemValue');
// the part will cause and error
$xml_a->addChild($xml_b);
$xml->addChild($xml_a);

我知道上面的代码不工作,但这将是我正在寻找的东西。

所以结构看起来像:

<root>
 <partent>
  <child attribute="value">
   <item>itemValue</item>
  </child>
 </parent>
</root>

我已经尝试使用下面的东西来addChild():

$dom = dom_import_simplexml($xml_a);
$_xml_ = $dom->ownerDocument->saveXML($dom->ownerDocument->documentElement);
$xml->addChild('parent',$_xml_);

解决方案我肯定是相对简单的,但我没有使用SimpleXMLElement这样的以前。

你不能用SimpleXML,但如果你真的需要操作你的DOM或从头开始创建它考虑DOMDocument。

$xmlObject   = new 'DOMDocument();
$xml = $xmlObject->createElement('root');
$xml_a = $xmlObject->createElement('parent');
$xml_b = $xmlObject->createElement('child');
$xml_b->setAttribute('attribute','value');
$xml_b->appendChild(new 'DOMElement('item', 'itemValue'));
$xml_a->appendChild($xml_b);
$xml->appendChild($xml_a);
$xmlObject->appendChild($xml);
echo $xmlObject->saveXML();