1

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.

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

2 Comments

@user2917823 yeah, i got confused also on your revision, i also made the changes accordingly, glad this helped
Thanx for the text hint! Really helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.