write to xml in php | add a node to existing xml in php | xml in php | How to update xml using php

I searched the web a lot to get a fix for this and struggled to get to the right solution. finally after going through so many sites, I got a solution and thought of sharing with you guys.

Before: books.xml

          first title
          second title

Assume we have an book.xml as above. Now all I need is based on user input I need to update or add a record node to books.xml.

Below are the steps to do this

1. Create index.php

   New Document 


Upon Submit it will take you to renderindex.php. So we need to create that file

2. Create a file called renderindex.php


$getTitle = $_POST['title'];

//Get the  tag
$games = $scores -> getElementsByTagName('records');

//Create the new  tag (Could probably be done better by first placing everything in an array or something)
$newrecord = $scores -> createElement("record");
$newrecord -> appendChild($scores -> createElement("title",$getTitle));

//Add the new  tag under the  tag
$games -> item(0) -> appendChild($newrecord);

//Save again
$scores -> save('books.xml');

Note: Once you have saved books.xml then you are done. don’t add below line as shown above
3. Now open index.php in browser, you can see a text box next to submit button. Add a title and do a submit.
4. Go back to your XML and see new record node with a title got added.

Hope this helps. Drop your comments if you like this


I Am suresh(suresh kumar )a Web developer,Freelancer,webdesigner,UI developer from bangalore. Got 6+ yrs of IT experience . I specialize in standards-based XHTML, CSS and JavaScript web development. Each site I develop is built to be search engine friendly (SEO), using the latest development principles and techniques.

You may also like...

1 Response

  1. Muqtada says:

    What if tag “records” does not exist in the document?

Leave a Reply

Your email address will not be published. Required fields are marked *