thinkphp自動生成sitemap網站站點地圖


首先用的是

米撲科技的開源項目:sitemap-php 自動生成網站地圖

使用方式可以去github上看文檔  https://github.com/mimvp/mimvp-sitemap-php

function testSitemap() {
    $sitemap = new \app\extra\Mysitemap("http://mimvp.com");
    
     $sitemap->addItem('/', '1.0', 'daily', 'Today');
     $sitemap->addItem('/hr.php', '0.8', 'monthly', time());
     $sitemap->addItem('/index.php', '1.0', 'daily', 'Jun 25');
     $sitemap->addItem('/about.php', '0.8', 'monthly', '2017-06-26');
     
     $sitemap->addItem('/hr2.php', '1.0', 'daily', time())->addItem('/index2.php', '1.0', 'daily', 'Today')->addItem('/about2.php', '0.8', 'monthly', 'Jun 25');
     
     $sitemap->endSitemap();
}

 

 

后台效果是自己做的

 

 

核心代碼:

首先在extra目錄下引入類文件

 

 Mysitemap.php

<?php
namespace app\extra;

use XMLWriter;

/**
 * Sitemap
 *
 * 生成 Google Sitemap files (sitemap.xml)
 *
 * @package    Sitemap
 * @author     Sandy <sandy@mimvp.com>
 * @copyright  2009-2017 mimvp.com
 * @license    http://opensource.org/licenses/MIT MIT License
 * @link       http://github.com/mimvp/sitemap-php
 */
class Mysitemap {

    private $writer;        // XMLWriter對象
    private $domain = "http://mimvp.com";            // 網站地圖根域名
    private $xmlFile = "sitemap";                    // 網站地圖xml文件(不含后綴.xml)
    private $xmlFileFolder = "";                    // 網站地圖xml文件夾
    private $currXmlFileFullPath = "";                // 網站地圖xml文件當前全路徑
    private $isSchemaMore= true;                    // 網站地圖是否添加額外的schema
    private $current_item = 0;                        // 網站地圖item個數(序號)
    private $current_sitemap = 0;                    // 網站地圖的個數(序號)

    const SCHEMA_XMLNS = 'http://www.sitemaps.org/schemas/sitemap/0.9';
    const SCHEMA_XMLNS_XSI = 'http://www.w3.org/2001/XMLSchema-instance';
    const SCHEMA_XSI_SCHEMALOCATION = 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd';
    const DEFAULT_PRIORITY = 0.5;
    const SITEMAP_ITEMS = 50000;
    const SITEMAP_SEPERATOR = '-';
    const INDEX_SUFFIX = 'index';
    const SITEMAP_EXT = '.xml';

    /**
     * @param string $domain    :    初始化網站地圖根域名
     */
    public function __construct($domain) {
        $this->setDomain($domain);
    }

    /**
     * 設置網站地圖根域名,開頭用 http:// or https://, 結尾不要反斜杠/
     * @param string $domain    :    網站地圖根域名 <br>例如: http://mimvp.com
     */
    public function setDomain($domain) {
        if(substr($domain, -1) == "/") {
            $domain = substr($domain, 0, strlen($domain)-1);
        }
        $this->domain = $domain;
        return $this;
    }

    /**
     * 返回網站根域名
     */
    private function getDomain() {
        return $this->domain;
    }

    /**
     * 設置網站地圖的xml文件名
     */
    public function setXmlFile($xmlFile) {
        $base = basename($xmlFile);
        $dir = dirname($xmlFile);
        if(!is_dir($dir)) {
            $res = mkdir(iconv("UTF-8", "GBK", $dir), 0777, true);
            if($res) {
//echo "mkdir $dir success";
            } else {
//echo "mkdir $dir fail.";
            }
        }
        $this->xmlFile = $xmlFile;
        return $this;
    }

    /**
     * 返回網站地圖的xml文件名
     */
    private function getXmlFile() {
        return $this->xmlFile;
    }

    public function setIsChemaMore($isSchemaMore) {
        $this->isSchemaMore = $isSchemaMore;
    }

    private function getIsSchemaMore() {
        return $this->isSchemaMore;
    }

    /**
     * 設置XMLWriter對象
     */
    private function setWriter(XMLWriter $writer) {
        $this->writer = $writer;
    }

    /**
     * 返回XMLWriter對象
     */
    private function getWriter() {
        return $this->writer;
    }

    /**
     * 返回網站地圖的當前item
     * @return int
     */
    private function getCurrentItem() {
        return $this->current_item;
    }

    /**
     * 設置網站地圖的item個數加1
     */
    private function incCurrentItem() {
        $this->current_item = $this->current_item + 1;
    }

    /**
     * 返回當前網站地圖(默認50000個item則新建一個網站地圖)
     * @return int
     */
    private function getCurrentSitemap() {
        return $this->current_sitemap;
    }

    /**
     * 設置網站地圖個數加1
     */
    private function incCurrentSitemap() {
        $this->current_sitemap = $this->current_sitemap + 1;
    }

    private function getXMLFileFullPath() {
        $xmlfileFullPath = "";
        if ($this->getCurrentSitemap()) {
            $xmlfileFullPath = $this->getXmlFile() . self::SITEMAP_SEPERATOR . $this->getCurrentSitemap() . self::SITEMAP_EXT;    // 第n個網站地圖xml文件名 + -n + 后綴.xml
        } else {
            $xmlfileFullPath = $this->getXmlFile() . self::SITEMAP_EXT;    // 第一個網站地圖xml文件名 + 后綴.xml
        }
        $this->setCurrXmlFileFullPath($xmlfileFullPath);        // 保存當前xml文件全路徑
        return $xmlfileFullPath;
    }

    public function getCurrXmlFileFullPath() {
        return $this->currXmlFileFullPath;
    }

    private function setCurrXmlFileFullPath($currXmlFileFullPath) {
        $this->currXmlFileFullPath = $currXmlFileFullPath;
    }

    /**
     * Prepares sitemap XML document
     */
    private function startSitemap() {
        $this->setWriter(new XMLWriter());
        $this->getWriter()->openURI($this->getXMLFileFullPath());    // 獲取xml文件全路徑

        $this->getWriter()->startDocument('1.0', 'UTF-8');
        $this->getWriter()->setIndentString("\t");
        $this->getWriter()->setIndent(true);
        $this->getWriter()->startElement('urlset');
        if($this->getIsSchemaMore()) {
            $this->getWriter()->writeAttribute('xmlns:xsi', self::SCHEMA_XMLNS_XSI);
            $this->getWriter()->writeAttribute('xsi:schemaLocation', self::SCHEMA_XSI_SCHEMALOCATION);
        }
        $this->getWriter()->writeAttribute('xmlns', self::SCHEMA_XMLNS);
    }

    /**
     * 寫入item元素,url、loc、priority字段必選,changefreq、lastmod可選
     */
    public function addItem($loc, $priority = self::DEFAULT_PRIORITY, $changefreq = NULL, $lastmod = NULL) {
        if (($this->getCurrentItem() % self::SITEMAP_ITEMS) == 0) {
            if ($this->getWriter() instanceof XMLWriter) {
                $this->endSitemap();
            }
            $this->startSitemap();
            $this->incCurrentSitemap();
        }
        $this->incCurrentItem();
        $this->getWriter()->startElement('url');
        $this->getWriter()->writeElement('loc', $this->getDomain() . $loc);            // 必選
        $this->getWriter()->writeElement('priority', $priority);                    // 必選
        if ($changefreq) {
            $this->getWriter()->writeElement('changefreq', $changefreq);            // 可選
        }
        if ($lastmod) {
            $this->getWriter()->writeElement('lastmod', $this->getLastModifiedDate($lastmod));    // 可選
        }
        $this->getWriter()->endElement();
        return $this;
    }

    /**
     * 轉義時間格式,返回時間格式為 2016-09-12
     */
    private function getLastModifiedDate($date=null) {
        if(null == $date) {
            $date = time();
        }
        if (ctype_digit($date)) {
            return date('c', $date);    // Y-m-d
        } else {
            $date = strtotime($date);
            return date('c', $date);
        }
    }

    /**
     * 結束網站xml文檔,配合開始xml文檔使用
     */
    public function endSitemap() {
        if (!$this->getWriter()) {
            $this->startSitemap();
        }
        $this->getWriter()->endElement();
        $this->getWriter()->endDocument();
        $this->getWriter()->flush();
    }

    /**
     * Writes Google sitemap index for generated sitemap files
     *
     * @param string $loc Accessible URL path of sitemaps
     * @param string|int $lastmod The date of last modification of sitemap. Unix timestamp or any English textual datetime description.
     */
    public function createSitemapIndex($loc, $lastmod = 'Today') {
        $indexwriter = new XMLWriter();
        $indexwriter->openURI($this->getXmlFile() . self::SITEMAP_SEPERATOR . self::INDEX_SUFFIX . self::SITEMAP_EXT);
        $indexwriter->startDocument('1.0', 'UTF-8');
        $indexwriter->setIndent(true);
        $indexwriter->startElement('sitemapindex');
        $indexwriter->writeAttribute('xmlns:xsi', self::SCHEMA_XMLNS_XSI);
        $indexwriter->writeAttribute('xsi:schemaLocation', self::SCHEMA_XSI_SCHEMALOCATION);
        $indexwriter->writeAttribute('xmlns', self::SCHEMA_XMLNS);
        for ($index = 0; $index < $this->getCurrentSitemap(); $index++) {
            $indexwriter->startElement('sitemap');
            $indexwriter->writeElement('loc', $loc . $this->getFilename() . ($index ? self::SITEMAP_SEPERATOR . $index : '') . self::SITEMAP_EXT);
            $indexwriter->writeElement('lastmod', $this->getLastModifiedDate($lastmod));
            $indexwriter->endElement();
        }
        $indexwriter->endElement();
        $indexwriter->endDocument();
    }

}

 

然后控制器里使用

 

function testSitemap() {
    $sitemap = new \app\extra\Mysitemap("http://mimvp.com");
    
     $sitemap->addItem('/', '1.0', 'daily', 'Today');
     $sitemap->addItem('/hr.php', '0.8', 'monthly', time());
     $sitemap->addItem('/index.php', '1.0', 'daily', 'Jun 25');
     $sitemap->addItem('/about.php', '0.8', 'monthly', '2017-06-26');
     
     $sitemap->addItem('/hr2.php', '1.0', 'daily', time())->addItem('/index2.php', '1.0', 'daily', 'Today')->addItem('/about2.php', '0.8', 'monthly', 'Jun 25');
     
     $sitemap->endSitemap();
}

 

我操作的時候遇到個坑,就是thinkphp報錯:XMLWriter 沒找到

一開始我以為是沒有裝XMLWriter擴展,phpinfo發現是有的,后來就在類文件Mysitemap.php,頭部加上

namespace app\extra;

use XMLWriter;

就可以了、

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM