使用 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();
是否可以插入一个 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();