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 ?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>
Consider the following fragment of code :
$xml = new DOMDocument();
$xml->load("C:\wamp\www\phpweb20\public\sitemap\sitemap.xml");
$root = $xml->firstChild;
$newElem = $xml->createElement('url');
$root->appendChild($newElem);
$txt = $xml->createTextNode("http://localhost/account/id/example");
$newElem->appendChild($txt);
$xml->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