PHP DOMDocument appendChild 到根目录末尾

标签 php xml domdocument appendchild

我有一个像这样格式化的 XML

<things>
  <thing>
    <name>foo</name>
    <id>1</id>
  </thing>
  <thing>
    <name>bar</name>
    <id>2</id>
  </thing>
</things>

我创建了一个新的 <thing>带有表单信息的元素。当我这样做时$dom->appendChild($newthing) ,它被附加到文档末尾的 </things>. 之后像这样

   <things>
     <thing>
        <name>foo</name>
        <id>1</id>
      </thing>
      <thing>
        <name>bar</name>
        <id>2</id>
      </thing>
    </things>
    <thing>
       <name>bar</name>
       <id>2</id>
    </thing>

显然我希望我的新元素成为根元素的子元素,而不是在它之后。我怎么做?

最佳答案

$dom->documentElement->appendChild($newthing);

来自PHP manual :

documentElement
This is a convenience attribute that allows direct access to the child node that is the document element of the document.

关于PHP DOMDocument appendChild 到根目录末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17863429/

相关文章:

php - php 中的 xml 解析 - 获取特定值

ruby - 比较 2 个数组,每个数组包含 200,000 多个值

android - 如何将 XML 转换为 Android 二进制 XML

php - PDO 在函数外工作,在函数内不起作用

PHP 和 MySQL - 高效处理多个一对多关系

php - 选择使用电子邮件地址

PHP DOMDocument : insertBefore, 如何让它工作?

multithreading - FreeThreadedDOMDocument,Neutral Apartments和Free-threaded Marshaler

Php - Dom,在 nodeValue 中插入 HTML_CODE

php - 不向数据库中插入数据