ロゴ メインコンテンツへ
RSSフィード
「Web 開発」に関連する記事一覧

PHPでサイトマップXMLを書き出すための補助クラス

2018/11/22 14:00
(この記事の文字数: 110)
PHP 

簡易的なものですが、PHPでサイトマップ用のXMLを作成するのが面倒だったので最低限の操作で済むように補助クラスを作成しました。ソースコードと使い方を掲載しておきます。

ソースコード


class SitemapXmlDoc
{
    private $xmlDoc = null;
    private $urlsetElem = null;

    public function __construct()
    {
        $this->xmlDoc = new DOMDocument("1.0", "UTF-8");
        $this->urlsetElem = new DOMElement("urlset");
        $this->xmlDoc->appendChild( $this->urlsetElem );
        $this->urlsetElem->setAttribute( 'xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9' );
    }

    public function addUrlElem($loc, $lastmod=null)
    {
        $url = new DOMElement("url");
        $this->urlsetElem->appendChild( $url );
        $loc = new DOMElement("loc", $loc);
        $url->appendChild( $loc );
        if ($lastmod != null)
        {
            $lastmod = new DOMElement("lastmod", $lastmod);
            $url->appendChild( $lastmod );
        }
    }

    public function save($outputXmlPath)
    {
        $this->xmlDoc->save($outputXmlPath);
    }
}

使用例

コード例


$doc = new SitemapXmlDoc();
$url = "http://puarts.com/";
$lastmod = date(DATE_W3C);
$doc->addUrlElem($url, $lastmod);
$doc->save('./sitemap.xml');

出力されるサイトマップの例



<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
	<url><loc>http://puarts.com/</loc><lastmod>2018-11-22T12:33:26+09:00</lastmod></url>
</urlset>

  このエントリーをはてなブックマークに追加  

<<「Web 開発」の記事一覧に戻る

コメント(0 件)



コンテンツロード: 0.0103 sec
Copyright(C)2006-2024 puarts All Rights Reserved