0

Here's my code:

public function write($txt){
              $randID = rand();
              $doc = new DOMDocument(); 
              $doc->formatOutput = true; 
              $doc->load($this->fileName); 
              $b = $doc->createElement( "input"); 
              $id = $doc->createElement( "id",$randID); 
              $b->appendChild($id);

              $text = $doc->createElement( "text",$txt); 
              $b->appendChild( $text ); 
              $doc->appendChild($b); 

              $doc->save($this->fileName); 

        }

Why does this code always overwrite the old file? Why doesn't it append to the end of the existing file? I'm new to XML with PHP :)

2
  • 2
    You are opening new DomDocument() rather than existing one with DomDocument::load() Commented Aug 19, 2011 at 11:01
  • 1
    Can you give an example of the file a) before you call the script, b) after the script is finished and c) the expected result? Commented Aug 19, 2011 at 11:30

1 Answer 1

2

I think it's because it just loads the file in memory, than adds the xml you want and than saves it to disk.

Because you use the same filename while saving, it overwrites the original file with a new file containing all XML, including the new elements and data. Makes sense to me.

Sign up to request clarification or add additional context in comments.

Comments

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.