=簡易メモ=
・TOPページと店舗一覧の圧縮サイトマップ(sitemap.xml.gz)をwebroot直下に作成する。
◯ 店舗用のテーブル定義
1 2 3 4 5 6 7 | // 店舗テーブル CREATE TABLE `shops` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(255) NOT NULL, `created` DATETIME DEFAULT NULL, `modified` DATETIME DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; |
◯ 「src/Shell/SitemapCreateShell.php」シェル作成
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 45 46 47 48 49 50 51 52 | <?php namespace App\Shell; use Cake\Console\Shell; use Cake\Filesystem\File; use Cake\ORM\TableRegistry; class SitemapCreateShell extends Shell { public function main() { // URL(トップページ) $site_url = 'https://cakephp3.com/'; // URL(店舗ページ) ex) https://cakephp3.com/shops/1 $shop_url = 'https://cakephp3.com/shops/'; // テーブルload $obj_shops = TableRegistry::get('shops'); // 店舗一覧取得 $data = $obj_shops->find('all')->toArray(); // sitemap.xml作成 $file = new File(WWW_ROOT . '/sitemap.xml', true); $file->write('<?xml version="1.0" encoding="UTF-8"?>' . "\n"); $file->write('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n"); $file->write(' <url>' . "\n"); $file->write(' <loc>' . $site_url . '</loc>' . "\n"); $file->write(' <priority>1.0</priority>' . "\n"); $file->write(' <lastmod>' . date('Y-m-d') . '</lastmod>' . "\n"); $file->write(' </url>' . "\n"); foreach ($data as $s_data) { $file->write(' <url>' . "\n"); $file->write(' <loc>' . $shop_url . $s_data['id'] . '</loc>' . "\n"); $file->write(' <priority>0.7</priority>' . "\n"); $file->write(' <lastmod>' . date('Y-m-d', strtotime($s_data['modified'])) . '</lastmod>' . "\n"); $file->write(' </url>' . "\n"); } $file->write('</urlset>' . "\n"); // sitemap.xml圧縮(sitemap.xml -> sitemap.xml.gz) $data = implode("", file(WWW_ROOT . '/sitemap.xml')); $gzdata = gzencode($data, 9); $fp = fopen(WWW_ROOT . '/sitemap.xml.gz', "w"); fwrite($fp, $gzdata); fclose($fp); // sitemap.xml削除 $file->delete(); } } |
◯ 「src/Shell/SitemapCreateShell.php」シェル実行
1 | # bin/cake SitemapCreate |
◯ 生成された「webroot/sitemap.xml.gz」ファイル例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>https://cakephp3.com/</loc> <priority>1.0</priority> <lastmod>2018-02-07</lastmod> </url> <url> <loc>https://cakephp3.com/shops/1</loc> <priority>0.7</priority> <lastmod>2018-02-07</lastmod> </url> <url> <loc>https://cakephp3.com/shops/2</loc> <priority>0.7</priority> <lastmod>2018-02-07</lastmod> </url> </urlset> |