【问题标题】:php - SimpleXMLElement insert xml contentphp - SimpleXMLElement 插入 xml 内容
【发布时间】:2013-12-17 09:49:37
【问题描述】:

说,我有以下 php 代码:

<?php

$resultXML = "<root><book></book></root>"; 
$resultXML = new SimpleXMLElement($resultXML);

?>

如何插入以下 XML: &lt;car&gt;&lt;bmw&gt;&lt;/bmw&gt;&lt;/car&gt; 以便我得到 &lt;root&gt;&lt;car&gt;&lt;bmw&gt;&lt;/bmw&gt;&lt;/car&gt;&lt;book&gt;&lt;/book&gt;&lt;/root&gt;

基本上,我想在现有XML 中插入一个元素(及其子元素、孙子元素等)的通用解决方案。有什么帮助吗?

【问题讨论】:

  • 很高兴看到您的尝试,以便我们帮助您找出问题所在。
  • @ÁlvaroG.Vicario 一种方法是循环遍历 xml 我想插入并使用 SimpleXMLElement::addChild 添加每个元素及其子元素(很难并且不能很好地扩展)。我能想到的另一种方法是使用字符串操作并在&lt;root&gt; 之后插入第二个xml。这看起来不像是一个干净的解决方案。

标签: php xml


【解决方案1】:

试试这个

$resultXML = new SimpleXMLElement('<root><book></book></root>');

            $car=$resultXML->addChild('car');

            $car->addChild('bmw');
            $resultXML->asXML('path/to/save/abc.xml');

【讨论】:

  • Basically, I want to generic solution to insert an element (with its children, grandchildren etc) in an existing XML. 您的回答假定我知道我要插入的 XML 的内容。
猜你喜欢
  • 2011-05-07
  • 2017-08-04
  • 1970-01-01
  • 2016-06-29
  • 2014-03-28
  • 2018-08-29
  • 2015-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多