http://php-archive.net/php/sitemap-generator/
上記ページのコードを参考にxmlサイトマップを自動で更新するプログラムを作成中です。
・sitemap_generator.php
<?php class SitemapGenerator{ private $sitemap; private $urlset = array(); function __construct(){ $this->sitemap = new DOMDocument('1.0', 'UTF-8'); $this->sitemap->preserveWhiteSpace = false; $this->sitemap->formatOutput = true; $this->urlset = $this->sitemap->appendChild( $this->sitemap->createElement("urlset") ); $this->urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9'); } function add($params){ $url = $this->urlset->appendChild( $this->sitemap->createElement('url') ); foreach($params as $key => $value){ if(strlen($value)){ $url->appendChild( $this->sitemap->createElement($key, $value) ); } } } function generate($file=null){ if( is_null($file) ) { header("Content-Type: text/xml; charset=utf-8"); echo $this->sitemap->saveXML(); } else { $this->sitemap->save( $file ); } } }
使用例
<?php include_once "sitemap_generator.php"; $sitemap = new SitemapGenerator(); $sitemap->add([ 'loc' => 'http://php-archive.net/', 'lastmod' => '2013-05-23', 'changefreq' => 'daily', 'priority' => '1.0' ]); $sitemap->add([ 'loc' => 'http://php-archive.net/category/php/', 'lastmod' => date('c'), 'changefreq' => 'monthly', 'priority' => '0.5' ]); $sitemap->generate(); ?>
参考ページには
「ページごとの url 要素を配列として add() に渡すと追加されます。」
とありますが、自動的に下記コードを追記していくにはどのようにしたらよいのでしょうか?
<?php $sitemap->add([ 'loc' => 'http://php-archive.net/category/php/', 'lastmod' => date('c'), 'changefreq' => 'monthly', 'priority' => '0.5' ]); ?>
何かヒントを頂けたら嬉しいです。
よろしくお願いいたします。
【追記】
新しくページを追加したタイミングで追加したいです。
ページの内容はデータベースに格納していて動的に生成しています。