在 yii2 中创建站点地图

create site map in yii2

我想在 yii2 中创建站点地图 我不知道我会做什么。 帮助我从哪里开始? 这是我的新闻模型 :

/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'news';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['news_cat_id', 'user_id','time'], 'integer'],
        [['news_dec'], 'string'],
        [['news_title', 'logo'], 'string', 'max' => 255]
    ];
}

我无法使用扩展,因为它没有好的文档。

  1. 安装包composer require evert/sitemap-php
  2. 在@app/commands/ 目录中为控制台应用程序创建命令控制器。

    class SitemapController 扩展控制器 {

    public function actionIndex(){
    
        $host = 'http://yoursitehost.com/';
    
        $sitemap = new Sitemap($host);
    
        $sitemap->setPath(Yii::getAlias('@webroot').DIRECTORY_SEPARATOR);
    
        $sitemap->addItem('', '1.0', 'daily', 'Today');
        $sitemap->addItem('news', '9.0', 'daily', 'Today');
    
        foreach(News::find()->batch(50) as $news){
            foreach($news as $n){
                $sitemap->addItem(Url::toRoute(['news/view', 'id' => $n->id]), '8.0', 'daily', 'Today');
            }
        }
    
        $sitemap->createSitemapIndex($host, 'Today');
    }
    

    }

  3. 将您的控制器添加到 console.php 配置文件。

    $配置=[ ... 'controllerMap' => [ 'sitemap' => [ 'class' => 'app\commands\SitemapController' ], ] ];

并添加到顶部console.php Yii::setAlias('@webroot', dirname(__DIR__) . '/../web');

  1. 运行 命令 php yii sitemap。脚本生成文件 sitemap.xml 到 web 目录。

  2. 前往 link - http://yourhost.com/sitemap.xml.

您可以通过 cron 运行 此命令 php yii sitemap