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 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分