Wednesday, 27 February 2013

Working with XML in PHP

Hey guys !! Writing an article after a long long time !! Been a month since i last wrote an article (courtesy mid semester exams) . So today i will give you a basic intro as to how you will load an xml file in php and add stuff to it . It's applications ? Well you may have a sitemap which is to be uploaded in real time as more links are added to your website . Or say you want to store data in xml format and would make an ajax call to the file etc .

 Example of a sitemap.xml file :-

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="">

So how can you open up and edit an XML File ?
Consider the following fragment of code :

$xml = new DOMDocument();

$root = $xml-&gt;firstChild;
$newElem = $xml-&gt;createElement('url');
$txt = $xml-&gt;createTextNode("http://localhost/account/id/example");

Let us consider the fragment of code line by line :
The first line creates a new object , which might be used to represent an entire HTML/XML document . Since both xml and html semantics are identical , so this can be used for creating/editing html too . The next line will load the file as given by the location . The next line selects the first child of the document root (since we specified $xml as document root in the first line , if you pass along any other element , the first child of that element will be selected) . In the example i cited above the element is selected . In the following line i create a new element with the name (like the other url's i created before as given in the example) . To push this new element into we use the appendChild method in the next line . Finally we have to populate the element with some contents , preferably in the form of text . For that we use the createTextNode method in the following line , followed by appendChild like before . Then the last and final , but the most important step , which is saving the file . For that we use the save method which takes as a parameter the path to the xml file .


  1. Thank for sharing the information, checkout my blog at
    feel free to leave a comment

  2. Informative. Many thanks for sharing these valuable information. Find my blog here

  3. Thank you for posting such a useful, impressive.your blog is so beautiful. you have give me great news.

    6 Month php Industrial Training in Chandigarh
    6 weeks php industrial training in chandigarh