PHP生成网站Sitemap,包含默认、分类、文章、标签、profile等
PHP.jpg<?php
namespace App\Libs;
use App\Services\ArticleService;
use App\Services\CategoryService;
use App\Services\TagService;
use App\Services\UserService;
class Sitemap {
public static $url = 'http://blog.getcoder.cn';
public static $defaultXml = [
[
'loc' => '/',
'priority' => 1.00,
],
[
'loc' => '/hot',
'priority' => 0.80,
],
[
'loc' => '/login',
'priority' => 0.80,
],
];
public static function createSitemap(){
// 创建一个DOMDocument对象
$dom = new \DOMDocument("1.0","utf-8");
header("Content-Type: text/xml");
// 创建根节点
$root = $dom->createElement("urlset");
$dom->appendChild($root);
//生成默认的Url
self::createUrl($root, $dom, self::$defaultXml);
//生成分类
$catList = CategoryService::getList();
$catXml = [];
if(!empty($catList)){
foreach ($catList as $item){
$catXml[] = [
'loc' => '/category?id=' . $item->id,
'priority' => 0.64,
'lastmod' => $item->update_time
];
}
}
self::createUrl($root, $dom, $catXml);
//生成文章
$articleList = ArticleService::getList();
$articleXml = [];
if(!empty($articleList)){
foreach ($articleList as $item){
$articleXml[] = [
'loc' => '/article?id=' . $item->id,
'priority' => 0.94,
'lastmod' => $item->update_time
];
}
}
self::createUrl($root, $dom, $articleXml);
//生成Tag
$tagList = TagService::getList();
$tagXml = [];
if(!empty($tagList)){
foreach ($tagList as $item){
$tagXml[] = [
'loc' => '/tag?id=' . $item->id,
'priority' => 0.64,
'lastmod' => $item->create_time
];
}
}
self::createUrl($root, $dom, $tagXml);
//生成用户主页
$userList = UserService::getList();
$userXml = [];
if(!empty($userList)){
foreach ($userList as $item){
$userXml[] = [
'loc' => '/profile?uid=' . $item->uid,
'priority' => 0.7,
'lastmod' => $item->create_time
];
}
}
self::createUrl($root, $dom, $userXml);
//生成xml文件
$dom->save(public_path() . "/sitemap.xml");exit;
}
public static function createUrl(&$root, &$dom, $data){
$date = date('Y-m-d');
foreach($data as $value){
// 建立根下子节点track
$track = $dom->createElement("url");
$root->appendChild($track);
// 建立track节点下元素
$loc = $dom->createElement("loc");
$priority = $dom->createElement("priority");
$lastmod = $dom->createElement("lastmod");
$changefreq = $dom->createElement("changefreq");
$track->appendChild($loc);
$track->appendChild($priority);
$track->appendChild($lastmod);
$track->appendChild($changefreq);
// 赋值
$locNode = $dom->createTextNode(self::$url.$value['loc']);
$date = empty($value['lastmod']) ? $date : date('Y-m-d', strtotime($value['lastmod']));
$lastmodNode = $dom->createTextNode($date);
$changefreqNode = $dom->createTextNode('daily');
$priorityNode = $dom->createTextNode($value['priority']);
$loc->appendChild($locNode);
$lastmod->appendChild($lastmodNode);
$changefreq->appendChild($changefreqNode);
$priority->appendChild($priorityNode);
}
}
}
网友评论