SitemapWriter.php 1.69 KB
<?php
/**
 * @author Bogdan Savluk <savluk.bogdan@gmail.com>
 * For more info about params see:
 * @link http://www.sitemaps.org/protocol.html
 */
class SitemapWriter
{
    const FREQ_ALWAYS = 0;
    const FREQ_HOURLY = 1;
    const FREQ_DAILY = 2;
    const FREQ_WEEKLY = 3;
    const FREQ_MONTHLY = 4;
    const FREQ_YEARLY = 5;
    const FREQ_NEVER = 6;
    private static $freq = array(
        'always',
        'hourly',
        'daily',
        'weekly',
        'monthly',
        'yearly',
        'newer');
    private $_pull = array();

    public function addPage($location, $lastmod = null, $changefreq = null, $priority = null)
    {
        $this->_pull[] = array(
            $location, $lastmod, $changefreq, $priority
        );
    }

    public function generateXml($processOutput = false)
    {
        if ($processOutput) {
            ob_start();
        }
        echo '<?xml version="1.0" encoding="UTF-8"?>',"\n",

        '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',"\n";

        foreach ($this->_pull as &$item) {
            echo "  ",'<url>',"\n    ",'<loc>', htmlentities($item[0]), '</loc>',"\n";
            if (isset($item[1])) {
                echo "    ",'<lastmod>', $item[1], '</lastmod>',"\n";
            }
            if (isset($item[1])) {
                echo "    ",'<changefreq>', self::$freq[$item[2]], '</changefreq>',"\n";

            }
            if (isset($item[1])) {
                echo "    ",'<priority>', $item[3], '</priority>',"\n";
            }
            echo "  ",'</url>',"\n";
        }
        echo '</urlset>';
        $res = null;
        if ($processOutput) {
            $res = ob_get_clean();
        }
        return $res;
    }
}