生成product详情页的sitemap,放到public目录下,3w条一个sitemap,例如 sitemap1.xml sitemap2.xml ..
php artisan make:command GenerateSitemap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| use Illuminate\Console\Command; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Storage; use App\Models\Item;
... public function handle() { $page = 1; $perPage = 30000; // 每页数量 do { $posts = Item::offset(($page - 1) * $perPage)->limit($perPage)->get(); if ($posts->count() <= 0) { break; } $sitemapContent = '<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
foreach ($posts as $key => $post) { $sitemapContent .= ' <url> <loc>' . url('/product/') .'/'. $post->id . '</loc> <lastmod>' . date('Y-m-d', strtotime($post->updated_at->tz('UTC')->toAtomString())) . '</lastmod> </url>'; } $sitemapContent .= ' </urlset>';
// Save sitemap.xml file to storage $storageFilePath = 'sitemap.xml'; Storage::put($storageFilePath, $sitemapContent);
// Copy sitemap.xml file from storage to public directory $publicFilePath = public_path('sitemap' . $page . '.xml'); File::copy(Storage::path($storageFilePath), $publicFilePath);
$this->info('Sitemap generated successfully at ' . $publicFilePath); $page += 1; } while ($posts->count() > 0); } ...
|