user2917823
user2917823

Reputation: 199

PHP XML append to created file

I have the following XML documment:

<list>
  <person>
     <name>Simple name</name>
  </person>
</list>

I try to read it, and basically create another "person" element. The output I want to achieve is:

<list>
  <person>
     <name>Simple name</name>
  </person>
  <person>
     <name>Simple name again</name>
  </person>
</list>

Here is how I am doing it:

$xml = new DOMDocument();
$xml->load('../test.xml');
$list = $xml->getElementsByTagName('list') ;

if ($list->length > 0) {
    $person = $xml->createElement("person");

    $name = $xml->createElement("name");        
    $name->nodeValue = 'Simple name again';

    $person->appendChild($name);
    $list->appendChild($person);
}

$xml->save("../test.xml");

What I am missing here?

Edit: I have translated the tags, so that example would be clearer.

Upvotes: 1

Views: 44

Answers (1)

Kevin
Kevin

Reputation: 41885

Currently, you're pointing/appending to the node list instead of that found parent node:

$list->appendChild($person);
// ^ DOMNodeList

You should point to the element:

$list->item(0)->appendChild($person);

Sidenote: The text can already put inside the second argument of ->createElement():

$name = $xml->createElement("name", 'Simple name again');

Upvotes: 1

Related Questions