StackOverflower StackOverflower - 1 year ago 100
PHP Question

PHP - Dynamically append web page to sitemap.xml

I have a site that searches through a database of websites. I am trying to get to append an url to sitemap.xml whenever the search returns a single result. I know I would need to use simplexml but I'm not sure how to implement it.

Pseudo Code

if (correct results) {
$theDate = date('c',time());
$theUrl = ""
appendtositemap($theDate, $theUrl);

Current sitemap.xml

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

Answer Source

You would first want to parse what you already have, if you're adding on to it:

$sitemap = simplexml_load_string(YOUR_ORIGINAL_XML_HERE_AS_A_STRING);

After that, let's say you want to create a new url node. You can do this by using the addChild function on any SimpleXMLElement (this creates a child XML node, or the nested node structure you see above):

$myNewUri = $sitemap->addChild("url");
$myNewUri->addChild("loc", "");
$myNewUri->addChild("lastmod", "2015-01-07T20:50:10+00:00");
$myNewUri->addChild("changefreq", "daily");
$myNewUri->addChild("priority", "2.0");

Here, the first property is always required; that's the name of the XML node that you're adding. The second parameter is optional, but it specifies the text value to add to the new node. Do this for each of the links and you'll keep appending nodes

Finally, you want to print it out, no? To do that, use:

echo $sitemap->asXml();

If you want to save it to a file instead: