PHP ZCE mock test, interview preparation, daily lessons under chalk talk

Friday, April 20, 2012

PHP sitemap.xml generation via DOMDocument


A Sitemap is an XML file that lists the URLs for a site. It allows webmasters to include additional information about each URL: when it was last updated, how often it changes, and how important it is in relation to other URLs in the site. This allows search engines to crawl the site more intelligently. 


An example of generating sitemap.xml using DomDocument is mentioned below:

$doc = new DOMDocument();
$doc->formatOutput = true;


$r = $doc->createElementNS( "http://www.sitemaps.org/schemas/sitemap/0.9","urlset" );
$r->setAttributeNS(
                'http://www.w3.org/2001/XMLSchema-instance',
                'xsi:schemaLocation',
                'http://www.sitemaps.org/schemas/sitemap/0.9             http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'
                );


$doc->appendChild( $r );
/**
* Home Page
**/
$b = $doc->createElement( "url" );
$loc = $doc->createElement("loc");
$loc->appendChild($doc->createTextNode($SITE_URL));
$b->appendChild( $loc );
        $priority = $doc->createElement( "priority" );
        $priority->appendChild(
                        $doc->createTextNode('1.0')
                        );
        $b->appendChild( $priority );


        $r->appendChild( $b );


        $changefreq = $doc->createElement( "changefreq" );
        $changefreq->appendChild(
                        $doc->createTextNode('Daily')
                        );
       $b->appendChild( $changefreq );

        $lastmod = $doc->createElement( "lastmod" );
        $lastmod->appendChild(
                        $doc->createTextNode(date('Y-m-d'))
                        );
        $b->appendChild( $lastmod );

        $r->appendChild( $b );
/** repeat this for all pages on your site **/
$output = $doc->saveXML();
header("Content-type:text/xml");
echo $output;

1 comment: