簡體   English   中英

PHP DOMDocument appendChild 到 root 的末尾

[英]PHP DOMDocument appendChild to end of root

我有一個像這樣格式化的 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 手冊

文檔元素
這是一個方便的屬性,允許直接訪問作為文檔的文檔元素的子節點。

嘗試

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

我必須達到同樣的目的,我已經這樣做了

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM