ejfrancis
ejfrancis

Reputation: 3045

PHP DOMDocument appendChild to end of root

I've got an XML formatted like so

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

And I've created a new <thing> element with info from a form. When I do $dom->appendChild($newthing), it's appended to the end of the document, after </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>

Obviously I want my new element to be a child of the root element, not after it. How do I do that?

Upvotes: 2

Views: 4194

Answers (3)

Vishv Shroff
Vishv Shroff

Reputation: 71

I have to achieve same thing and I have done like this

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

Upvotes: 0

PleaseStand
PleaseStand

Reputation: 32122

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

From the PHP manual:

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

Upvotes: 2

JohnnyFaldo
JohnnyFaldo

Reputation: 4161

try

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

Upvotes: 1

Related Questions