2

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

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

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

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

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

4

3 回答 3

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

PHP 手册

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

于 2013-07-25T16:19:28.437 回答
1

尝试

$dom->appendChild($dom->createElement($newthing));
于 2013-07-25T16:19:06.460 回答
0

我必须实现同样的目标,我已经这样做了

$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]
于 2020-05-23T12:48:03.650 回答