Sitemap.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\App;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\URL;
  7. class Sitemap extends Command
  8. {
  9. /**
  10. * The name and signature of the console command.
  11. *
  12. * @var string
  13. */
  14. protected $signature = 'sitemap:generate';
  15. /**
  16. * The console command description.
  17. *
  18. * @var string
  19. */
  20. protected $description = 'generate sitemap.';
  21. /**
  22. * Create a new command instance.
  23. *
  24. */
  25. public function __construct()
  26. {
  27. parent::__construct();
  28. }
  29. protected function generate()
  30. {
  31. $domain = config('APP_URL', '');
  32. // create new sitemap object
  33. $sitemap = App::make("sitemap");
  34. // add items to the sitemap (url, date, priority, freq)
  35. $sitemap->add(URL::to('/'), date("Y-m-d\TH:i:s+00:00", time()), '0.8', 'daily');
  36. $articles = DB::select("select id, slug from blog_articles");
  37. $tags = DB::select("select id, tag_name from blog_tags");
  38. $categories = DB::select("select id, cate_name from blog_categories");
  39. foreach ($articles as $article) {
  40. $url = $domain.'/'.$article->slug;
  41. $sitemap->add(URL::to($url), date("Y-m-d\TH:i:s+00:00", time()), '0.8', 'daily');
  42. }
  43. foreach ($tags as $tag) {
  44. $url = $domain.'/tag/'.$tag->tag_name;
  45. $sitemap->add(URL::to($url), date("Y-m-d\TH:i:s+00:00", time()), '0.8', 'daily');
  46. }
  47. foreach ($categories as $category) {
  48. $url = $domain.'/category/'.$category->cate_name;
  49. $sitemap->add(URL::to($url), date("Y-m-d\TH:i:s+00:00", time()), '0.8', 'daily');
  50. }
  51. // generate your sitemap (format, filename)
  52. $sitemap->store('xml', 'sitemap_20200520');
  53. }
  54. /**
  55. * Execute the console command.
  56. *
  57. * @return mixed
  58. */
  59. public function handle()
  60. {
  61. $this->info('Generating sitemap...');
  62. $this->generate();
  63. }
  64. }