【问题标题】:PHP DOMDocument appendChild to end of rootPHP DOMDocument appendChild 到根目录的末尾
【发布时间】:2013-07-25 16:14:55
【问题描述】:

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

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

我创建了一个新的&lt;thing&gt; 元素,其中包含来自表单的信息。当我做$dom-&gt;appendChild($newthing)时,它被附加到文档的末尾,在&lt;/things&gt;.之后像这样

   <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>

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

【问题讨论】:

    标签: php xml domdocument appendchild


    【解决方案1】:
    $dom->documentElement->appendChild($newthing);
    

    来自PHP manual

    documentElement
    这是一个方便属性,允许直接访问作为文档的文档元素的子节点。

    【讨论】:

    • 谢谢!我花了 25 分钟在谷歌上搜索,没有一个结果提到 documentElement
    【解决方案2】:

    试试

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

    【讨论】:

      【解决方案3】:

      我必须做到同样的事情,我已经这样做了

      $xml = simplexml_load_file("customer.xml");
      foreach($xml->children() as $customer)
      {
          if($email == $customer->email)
          {
              $error = true;
              $message = "Email Already Exist";
              break;
          }
          $id = $customer->id + 1;
      }
      
      $customer = $xml->addChild('customer');
      $xml_id = $customer->addChild('id',$id);
      $xml_firstName = $customer->addChild('firstName',$firstname);
      $xml_lastName = $customer->addChild('lastName',$lastname);
      $xml_email = $customer->addChild('email',$email);
      $xml_password = $customer->addChild('password',$password);
      $xml_contactNumber = $customer->addChild('contactNumber',$contactNumber);
      $fp = fopen('customer.xml','w');
      fwrite($fp,$xml->asXML());
      fclose($fp);`[![output file][1]][1]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-05
        • 1970-01-01
        • 1970-01-01
        • 2015-08-11
        • 1970-01-01
        相关资源
        最近更新 更多