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="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>localhost/account/id/nraider0207</url>
<url>localhost/account/id/anuragdas</url>
</urlset>


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


$xml = new DOMDocument();
$xml-&gt;load("C:\wamp\www\phpweb20\public\sitemap\sitemap.xml");

$root = $xml-&gt;firstChild;
$newElem = $xml-&gt;createElement('url');
$root-&gt;appendChild($newElem);
$txt = $xml-&gt;createTextNode("http://localhost/account/id/example");
$newElem-&gt;appendChild($txt);
$xml-&gt;save("C:\wamp\www\phpweb20\public\sitemap\sitemap.xml");


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 .


2 comments:

  1. Thank for sharing the information, checkout my blog at
    http://definingwords.blogspot.com/2013/03/coal.html
    feel free to leave a comment

    ReplyDelete
  2. Informative. Many thanks for sharing these valuable information. Find my blog here http://kangraavalley.blogspot.in/

    ReplyDelete