我想创建一个站点地图,但我对站点地图的使用知之甚少。我使用CakePHP。虽然在谷歌上有很多软件和指南,但我仍然想要询问一个简单的方法来为CakePHP创建站点地图。
我已经将网站上传到服务器上,它不依赖本地主机。
我已经将网站上传到服务器上,它不依赖本地主机。
这里提供一个简单的示例供您使用,并根据您的需要进行调整:
在您的控制器中:
public $components = array('RequestHandler');
public function sitemap()
{
Configure::write('debug', 0);
$articles = $this->Article->getSitemapInformation();
$this->set(compact('articles'));
$this->RequestHandler->respondAs('xml');
}
你的“文章”模型:
public function getSitemapInformation()
{
return $this->find('all', array(/* your query here */));
}
视图:
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($articles as $article): ?>
<url>
<loc><?php echo Router::url(/* generate the URLs here */); ?></loc>
<lastmod><?php echo $time->toAtom(/* last update time here */); ?></lastmod>
<changefreq>weekly</changefreq>
</url>
<?php endforeach; ?>
</urlset>
Router::parseExtensions('xml');
到 routes.php 文件中。接下来你需要创建一个路由,例如:Router::connect('/sitemap', array('controller' => 'posts' ....., 'ext' => 'xml'))
,它会将 site.com/sitemap.xml 重定向到包含站点地图的控制器/动作。请创建一个正确标题的 XML 布局,并将视图文件移动到 views/posts/xml/file.ctp。Router::parseExtensions('xml');
(不要拼错)<?php
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
echo $this->fetch('content');
echo '</urlset>';
?>
步骤2. 为网站地图生成创建一个单独的控制器:
class SitemapsController extends AppController
{
public function index()
{
$this->viewBuilder()->setLayout('sitemap');
$this->RequestHandler->respondAs('xml');
$postTbl = TableRegistry::getTableLocator()->get('Posts');
$posts = $postTbl->find()->select(['slug']);
$this->set('posts', $posts);
//Get the base URL of your website
$url = Router::url('/', true);
$this->set('url', $url);
}
}
步骤3. 创建一个包含XML标签的索引操作视图文件:index.ctp
<url>
<loc><?= $url; ?></loc>
<changefreq>weekly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc><?= $url; ?>contact-us</loc>
<priority>0.5</priority>
</url>
<url>
<loc><?= $url; ?>above-us</loc>
<priority>0.5</priority>
</url>
<url>
<loc><?= $url; ?>service</loc>
<priority>0.5</priority>
</url>
<?php foreach($osts as $post){?>
<url>
<loc><?php echo $url.'blog/'.$post['slug'] ?></loc>
</url>
<?php } ?>
步骤4. 在routes.php中添加一个sitemap路由:
Router::scope('/', function (RouteBuilder $routes) {
// Other routes.
$routes->connect('/sitemap.xml',['controller'=>'Sitemaps','action'=>'index']);
});
如果您想了解详细的教程,可以访问此教程,并逐步学习如何在CakePHP中创建XML站点地图。