duanliaogui4133 2016-09-16 10:32
浏览 28
已采纳

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

Is it possible to insert a PHP SimpleXMLElement as a child of another Element

$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);

I know the above code doesn't work, but that would be the sort of thing I'm looking for.

So that the structure looks like:

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

I have tried using something like the below to addChild() :

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

The solution im sure is relatively simple, but I've not used SimpleXMLElement like this before.

  • 写回答

1条回答 默认 最新

  • dsfykqq3403 2016-09-16 11:03
    关注

    You can't with SimpleXML, but if you really need manipulate your DOM or create it from scratch consider 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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错