Search code examples
phpsimplexmlsitemap

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 = "http://myurl.com/?r=asdfasdf1234"
    appendtositemap($theDate, $theUrl);
}

Current sitemap.xml

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>http://example.com/</loc>
        <lastmod>2013-04-08T20:38:15+00:00</lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
</urlset>

Solution

  • 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", "http://www.google.com/");
    $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:

    $sitemap->asXml("sitemap.xml");