laravel 生成网站地图

暂无标签

路由

Route::get('make-sitemap/{type}', [App\Http\Controllers\SitemapController::class, 'map'])->name('make.map');

控制器

SitemapController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Node;
use App\Models\Article;

class SitemapController extends Controller
{
  public function map($type) {
    $xml = $this->sitemap($type);
    $file = fopen('sitemap/'.$type.'-sitemap.xml', 'w');
    fwrite($file, $xml);
    fclose($file);
    return redirect('/')->with('success', __('Create success'));
  }
 
  private function sitemap($type) {
    $xml = '<?xml version="1.0" encoding="utf-8"?>';
    $xml .= '<urlset>';

    switch($type){
        case 'node':
            $nodes = Node::all();
            foreach($nodes as $node) {
              $xml .= $this->execute_xml(route('node.item',['node'=>$node->slug]),'weekly','0.8');
            }
          break;
           
          case 'article':
              Article::chunk(500, function($articles) use(&$xml) {
              foreach($articles as $article) {
                $xml .= $this->execute_xml(route('article.show',['article'=>$article->alias]),'daily','0.9');
              }
            });
          break;
    }
 
    $xml .= '</urlset>';
    return $xml;
  }
 
  private function execute_xml($url,$frequency,$importance) {
    $xml_url = '<url>';
    $xml_url .= '<loc>'.$url.'</loc>';
    $xml_url .= '<lastmod>'. date("Y-m-d", time()) .'</lastmod>';
    $xml_url .= '<changefreq>'.$frequency.'</changefreq>';
    $xml_url .= '<priority>'.$importance.'</priority>';
    $xml_url .= '</url>';
    return $xml_url;
  }
 
}

目录

在public里新建目录sitemap

访问/make-sitemap/article生成文章地图文件