Reputation: 1
I am facing a problem in editing a xml file.
<?xml version="1.0" encoding="UTF-8"?>
<urlset>
<url>
<loc>http://www.abc.com/</loc>
<lastmod>2010-04-17T17:23:57+00:00</lastmod>
<changefreq>daily</changefreq>
<priority>0.50</priority>
</url>
<url>
<loc>http://www.abc.com/</loc>
<lastmod>2010-04-17T17:23:57+00:00</lastmod>
<changefreq>daily</changefreq>
<priority>0.50</priority>
</url>
</urlset>
I want to add one more set of records starting with <url>
with its other tags, (i.e) "loc,lastmod,changefreq,priority" and than save the xml file.For adding the new record i need to remove the parent closing tag that is </urlset>
and than add the rest of the records and close the main tag.
Can anyone please help me solving my problem.Thanks
Upvotes: 0
Views: 1206
Reputation: 28648
Approach #1: Well, you can use SimpleXMLElement::xpath in order to retrieve urlset node and then use SimpleXMLElement::addChild to add the nodes you want.
Link: http://php.net/manual/en/book.simplexml.php
Approach #2 (easy one but not recommended): Use str_replace on "</urlset>" this way:
$xmlDoc = str_replace("</urlset>", "<!-- YOURXML--></urlset>", $xmlDoc);
Either way it should not be hard.
Upvotes: 1
Reputation: 4521
$dom = new DomDocument('1.0', 'utf-8');
$dom->loadXML($xml); // if it's a string, $dom->load($xmlFile) if is a file
// create the new node element
$node = $dom->createElement('url');
// build node
$node->appendChild($dom->createElement('loc', 'loc value'));
$node->appendChild($dom->createElement('lastmode', 'lastmod value'));
// (...)
// append the child node to the root
$dom->documentElement->appendChild($node);
// get the document as an XML string
$xmlStr = $dom->saveXML();
Upvotes: 0