Create an xml sitemap in php with fixed set of urls

Create an xml sitemap in php with fixed set of urls

Xml sitemap is used by crawlers like Google to determine which pages are present on the website. It is like a menu for a vast site. The xml sitemap can be submitted in tools like google webmaster to fasten the process and monitor the indexing of the various pages on the website.

If you a using an open source CMS like wordpress, you have a whole set of plugins at your disposal to create such xml sitemaps and keep updating it dynamically. But without any ready-made plugins in frameworks like Codeigniter, it is difficult to generate such type of xml sitemaps, especially when the number of  site urls are huge. It is definitely not possible and not feasible to generate them manually.

I have come up with a simple code that can help you solve this problem. I have written the code in Php Codeigniter but the function can be used in any php framework.

Here is the code

class Xml_creator extends CI_Controller
{
    public function __construct()
    {
    }
    public function create_sitemap()
    {
        $url_list = array(
           "http://www.roshnidevadiga.net/exciting-new-features-in-php-7/",
           "http://www.roshnidevadiga.net/inheritance-in-javascript/",
           "http://www.roshnidevadiga.net/google-whacking-tips-to-get-relevant-results-from-google/",
           "http://www.roshnidevadiga.net/improve-google-pagespeed/"
        );
        
        $xml_result = '<?xml version="1.0" encoding="UTF-8"?>
                     <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        
         foreach ($url_list as $url)
        {
            $xml_result .= '<url>';
            $xml_result .= '<loc>'.$url.'/</loc>';
            $xml_result .= '<priority>0.4</priority>';
            $xml_result .= '</url>';
        }
        $xml_result .= '</urlset>';
        $dom = new DOMDocument;
        $dom->preserveWhiteSpace = FALSE;
        $dom->loadXML($xml_result);
        $dom->formatOutput = TRUE;
        echo $dom->saveXml();
    }
}

Here you need to mention the urls of your website in $url_list array and run this php code. The xml sitemap will be printed in the browser which you can copy into a file and save it with .xml extension.

You can then upload it in the root folder of your site and enter its link in Google webmaster’s sitemap section. Your sitemap.xml will be ready to be crawled by Google and your urls will be indexed gradually.

Hope this was useful to you. Do let me know your feedback.

Comments are closed.