Skip to content

Instantly share code, notes, and snippets.

@devster
Created March 21, 2012 17:14
Show Gist options
  • Save devster/2149677 to your computer and use it in GitHub Desktop.
Save devster/2149677 to your computer and use it in GitHub Desktop.
Helper sitemap xml
<?php
/**
* SiteMapXML
*
* A simple helper to make simple sitemap.xml with images
*
* Usage:
* // without images
* $sitemap = new SiteMapXML();
* $sitemap->addUrl('http://example.org');
* $sitemap->saveXML() // returns the string xml
*
* // with images
* $node = $sitemap->addUrl('http://example.org');
* $sitemap->addImage($node, 'image url', 'image title', 'image alt');
*
* @author Jeremy Perret <jerem@devster.org>
*/
class SiteMapXML extends \DOMDocument
{
public $root;
public function __construct($charset = 'UTF-8')
{
parent::__construct('1.0', $charset);
$this->root = $this->appendChild($this->createElement('urlset'));
$xmlns = $this->createAttribute('xmlns');
$xmlns->value = 'http://www.sitemaps.org/schemas/sitemap/0.9';
$this->root->appendChild($xmlns);
$this->createAttributeNS('http://www.google.com/schemas/sitemap-image/1.1', 'image:attr' );
}
public function addUrl($url)
{
$urlNode = $this->createElement('url');
$this->root->appendChild($urlNode);
$urlNode->appendChild($this->_createTextNode('loc', $url));
return $urlNode;
}
public function addImage(\DOMElement $node, $url, $title, $catpion)
{
$imgNode = $this->createElement('image:image');
$node->appendChild($imgNode);
$imgNode->appendChild($this->_createTextNode('image:loc', $url));
$imgNode->appendChild($this->_createTextNode('image:title', $title));
$imgNode->appendChild($this->_createTextNode('image:caption', $catpion));
}
protected function _createTextNode($name, $value)
{
$el = $this->createElement($name);
$el->appendChild($this->createTextNode($value));
return $el;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment