laravel 网站地图轮子

本文介绍如何使用 Laravelium/sitemap 包在 Laravel 框架中自动化生成站点地图 (sitemap)。通过 Composer 安装指定版本的 sitemap 包,针对不同版本的 Laravel 进行适配。文章详细展示了如何配置并使用该包,包括将所有已审核的新闻条目添加到 sitemap 中,设置缓存和更新频率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://github.com/Laravelium/laravel-sitemap

add the following to your composer.json file :

For Laravel 5.7

"laravelium/sitemap": "3.0.*"

For Laravel 5.6

"laravelium/sitemap": "2.8.*"

For Laravel 5.5

"laravelium/sitemap": "2.7.*"

Publish needed assets (styles, views, config files) :

php artisan vendor:publish --provider="Laravelium\Sitemap\SitemapServiceProvider"

Note: Composer won't update them after composer update, you'll need to do it manually!

public function sitemap(Request $request) {
        // create new sitemap object
        $sitemap = App::make("sitemap");
        $sitemap->setCache('laravel.sitemap', 60);
        // get all posts from db
        $posts = News::where('audit_status', 0)
            ->orderBy('id', 'desc')
            ->get();
        // add every post to the sitemap
        foreach ($posts as $post) {

            $sitemap->add(getenv('APP_URL')."/news/".$post->id.'.html', $post->created_at, 0.9, 'monthly');
        }

        $sitemap->add(getenv('APP_URL')."/news.html", $post->created_at, 1, 'monthly');

        $xml=$sitemap->render('xml');

//        header('Content-Type: application/xml');
//        header('Content-Disposition: attachment;filename="sitemap.xml"');
        $path=public_path()."\sitemap.xml";
        $path=str_replace('\\','/',$path);

        return file_put_contents($path,$xml->getContent());
    }

转载于:https://www.cnblogs.com/sgm4231/p/10186748.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值