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 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,