Create Google XML (Image) Sitemaps in PHP

Ever wanted to create a Google XML Image Sitemap?

This is how it could be done with PHP:

header("Content-type: text/xml; charset=utf-8");
//create your XML document, using the namespaces
$urlset = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="" xmlns:image="" /><!--?xml version="1.0" encoding="UTF-8"?-->');
//iterate over your sites pages or whatever you like
foreach (getMyPagesOrWhatEver() as $item):
//add the page URL to the XML urlset
$url = $urlset->addChild('url');
$url->addChild('loc', $item->URL );
$url->addChild('lastmod', $item->LASTMOD );
$url->addChild('changefreq', 'daily');  //weekly etc.
$url->addChild('priority', '1.0');
//add an image
if ( $item->IMAGE ):
$image = $url->addChild('image:image', null, '');
$image->addChild('image:loc',$item->IMAGE->URL, '');
$image->addChild('image:caption',$item->IMAGE->ALT_OR_TITLE , '');
//add whitespaces to xml output (optional, of course)
$dom = new DomDocument();
$dom->formatOutput = true;
//output xml
echo $dom->saveXML();

That’s about it.

I found it kind of tricky to figure out how to use googles namespaces when working with SimpleXML, so hopefully this might help someone :)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.