自定义站点地图的xml文件

1 编写Sitemap类

<?php

class Sitemap
{
public $encoding; // xml编码

/**
* 初始化
* @param string $encoding xml编码
*/
public function __construct($encoding = 'UTF-8')
{
$this->encoding = $encoding;
}

/**
* 创建RSS文件内容
* @param array $items 文章内容
* return string rss字符串内容
*/
public function createSiteMap($items)
{
// 获取头部信息
$header = $this->getHeader();
// 获取文章信息
$items = $this->getItems($items);
return str_replace('<item>', $items, $header);
}

/**
* 获取item信息
* @param array $articles 文章内容,二维数组,格式[['loc' => '', 'priority' => '', 'lastmod' => '', 'changefreq' => ''],...]
* return string
*/
public function getItems($articles = [])
{
$items = "";
foreach ($articles as $k => $v) {
$items .= "\t\t".'<url>'."\n"; $items .= "\t\t\t".'<mobile:mobile type="pc,mobile"/>'."\n"; $items .= "\t\t\t".'<loc>'.$v['loc'].'</loc>'."\n";
$items .= "\t\t\t".'<priority>'.$v['priority'].'</priority>'."\n";
$items .= "\t\t\t".'<lastmod>'.$this->getDataTime($v['lastmod']).'</lastmod>'."\n";
$items .= "\t\t\t".'<changefreq>'.$v['changefreq'].'</changefreq>'."\n";
$items .= "\t\t".'</url>'."\n";
}
return $items;
}


// 获取头部信息
public function getHeader()
{
$header = '<?xml version="1.0" encoding="'.$this->encoding.'"?>'."\n";
$header .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/">'."\n".'<item>'."\n".'</urlset>'."\n";
return $header;
}

/**
* 格式化时间
* @param string $datetime 时间戳
* return string 时间,格式:2024-01-12 16:45:30
*/
public function getDataTime($datetime)
{
return date('Y-m-d H:i:s', $datetime);
}
}

2 使用Sitemap类

$encoding       = 'UTF-8';
$rss = new Sitemap($encoding);
$items = [
['loc' => 'https://www.cyanhui.com', 'priority' => '1.0', 'lastmod' => '1677290677', 'changefreq' => 'Always'],
['loc' => 'https://www.cyanhui.com/detail/324.html', 'priority' => '0.8', 'lastmod' => '1677290675', 'changefreq' => 'Always']
];
header('Content-Type: application/xml; charset=UTF-8');
echo $rss->createSiteMap($items);

3 查看结果



相关推荐

  • 生成图片

    from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageFilterdef create_image_with_text(size, color, text, font_path, font_size, text_color, shadow_color, output_path): """ Create a new image of specified size and color with centered text that has a border and shadow. :param size: A tuple con

  • 获取指定目录下的所有图片信息

    1 获取指定目录下的所有图片信息// 获取指定目录下的所有图片信息 public function getImagesInfo($directory) { $images = []; // 创建递归目录迭代器 $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY ); // 遍历目录中的每个文件 foreach (

  • Thinkphp各版本的PHP要求

    ThinkPHP 8.0:运行环境要求PHP8.0+,兼容PHP8.3ThinkPHP 6.1:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 6.0:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 5.1:运行环境要求PHP5.6+,兼容PHP8.0ThinkPHP 5.0:运行环境要求PHP5.4+,兼容PHP7.3