sitemapxml文件生成(代码片段)

fanfan259 fanfan259     2023-03-08     465

关键词:

sitemap xml生成方法


<?php
/**
 * SitemapService.php.
 *
 * 生成sitemap
 */

class Sitemap

    public $newLine = "
";
    public $indent = " ";
    public $xmlHeader = "<?xml version="1.0" encoding="UTF-8"?>
";
    public $urlsetOpen = "<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
";
    public $urlsetValue = "";
    public $urlsetClose = "</urlset>
";

    public $rootUrl = "";
    public function __construct($rootUrl = "https://www.xxx")
    
        if (empty($rootUrl)) 
            $rootUrl = "https://www.xxx";
        
        $this->rootUrl = $rootUrl;
    

    private function makeUrlString ($urlString) 
        return htmlentities($urlString, ENT_QUOTES|ENT_XML1, 'UTF-8');
    

    /**
     * 返回格式: 2019-02-01T12:40:05+00:00
     * 参数格式: 2019-02-01 12:40:05
     * @param $dateTime
     * @return bool|string
     */
    private function makeIso8601TimeStamp ($dateTime) 
        if (!$dateTime) 
            $dateTime = date('Y-m-d H:i:s');
        
        if (is_numeric(substr($dateTime, 11, 1))) 
            $isoTS = substr($dateTime, 0, 10) ."T"
                .substr($dateTime, 11, 8) ."+00:00";
         else 
            $isoTS = substr($dateTime, 0, 10);
        
        return $isoTS;
    

    private function makeUrlTag ($url, $modifiedDateTime, $changeFrequency, $priority) 
        $newLine = $this->newLine;
        $indent = $this->indent;

        $urlOpen = "$indent<url>$newLine";
        $urlClose = "$indent</url>$newLine";
        $locOpen = "$indent$indent<loc>";
        $locClose = "</loc>$newLine";
        $lastmodOpen = "$indent$indent<lastmod>";
        $lastmodClose = "</lastmod>$newLine";
        $changefreqOpen = "$indent$indent<changefreq>";
        $changefreqClose = "</changefreq>$newLine";
        $priorityOpen = "$indent$indent<priority>";
        $priorityClose = "</priority>$newLine";

        $urlTag = $urlOpen;
        $urlValue = $locOpen .$this->makeUrlString($url) .$locClose;
        if ($modifiedDateTime) 
            $urlValue .= $lastmodOpen .$this->makeIso8601TimeStamp($modifiedDateTime) .$lastmodClose;
        
        if ($changeFrequency) 
            $urlValue .= $changefreqOpen .$changeFrequency .$changefreqClose;
        
        if ($priority) 
            $urlValue .= $priorityOpen .$priority .$priorityClose;
        
        $urlTag .= $urlValue;
        $urlTag .= $urlClose;
        return $urlTag;
    

    /**
     * 验证是否符合url格式
     * url format: /xxx|lastmod|changefreq|priority
     *
     * @param $pageLine
     * @return bool
     */
    private function validateEntry ($pageLine) 
        $page = explode("|", $pageLine);
        $url = trim($page[0]);
        $processLine = TRUE;
        if (substr($url, 0, 1) != "/") 
            $processLine = FALSE;
        
        return $processLine;
    

    /**
     * 获取待生成的链接
     * url format: /xxx|lastmod|changefreq|priority
     *
     * @return array
     */
    private function getUrls()
    
        $lastmod = date('Y-m-d H:i:s');
        $changefreq = "daily";
        $priority_index = "1.0";
        $priority_category = "0.8";
        $priority_details = "0.5";
        $pageList = [];
        $pageList[] = "/|$lastmod|$changefreq|$priority_index";
        // 添加自己的网站url
        $pageList[] = "/ranking|$lastmod|$changefreq|$priority_category";
        return $pageList;
    

    /**
     * 生成sitemap文件
     */
    public function generate()
    
        $pageList = $this->getUrls();
        foreach($pageList as $pageLine) 
            $processLine = $this->validateEntry ($pageLine);
            $page = explode("|", $pageLine);
            $url = trim($page[0]);
            if ($processLine) 
                $this->urlsetValue .= $this->makeUrlTag ($this->rootUrl .$url, trim($page[1]),   trim($page[2]), trim($page[3]));
            
        
        return $this->xmlHeader . $this->urlsetOpen . $this->urlsetValue . $this->urlsetClose;
    


/**
 * 1. Sitemap 构造方法,默认的rootUrl 修改为待整理的网站域名
 * 2. Sitemap getUrls方法,添加自己网站的url
 * 3. 调用Sitemap时,rootUrl的参数修改
 */

$rootUrl = ""; 
$sitemap = new Sitemap($rootUrl);
$xml_data = $sitemap->generate();
header('Content-type: application/xml; charset="utf-8"');
echo $xml_data;

参考链接

谷歌帮助文档
sitemap xml格式
谷歌seo优化

生成csv文件(代码片段)

/***生成csv文件*filePath设置路径及文件名称*/@OverridepublicQWResultDatareplaceDepartment(StringfilePath)QWResultDataqwResultData=newQWResultData();List<String[ 查看详情

pythonpythonsnipet允许生成重复文件(代码片段)

查看详情

jupyternotebook生成py文件(代码片段)

在一个jupyternotebook中代码最后写入:并将jupyternotebook的文件名称也改为设定的文件名,最后执行以下代码即可生成。try:!jupyternbconvert--topython文件名except:pass  查看详情

markdown自述文件生成器(代码片段)

查看详情

text组件,模块,路由文件生成(代码片段)

查看详情

sh生成示例文件#fastq(代码片段)

查看详情

markdown生成手动po文件(代码片段)

查看详情

js生成下载文件(代码片段)

/***生成下载文件*@paramObjectfilename*@paramObjecttext*/functiondownload(filename,text)varpom=document.createElement(\'a\');pom.setAttribute(\'href\',\'data:text/plain;charset=utf-8,\'+encodeURIComponent(te 查看详情

sh生成虚拟文件和文件夹结构(代码片段)

查看详情

多图片生成pdf文件(代码片段)

这里记录多个图片合并生成一个pdf文件的方法。@TestpublicvoidexportTest()throwsIOException,DocumentException//图片文件夹地址StringimageFolderPath="F:/imgtest/";//图片地址StringimagePath=null;//PDF文件保存地址StringpdfPath="F:/ceshi.pdf";Fi 查看详情

通过ifm生成域配置文件(代码片段)

ntdsutilactivateinstancentdsifmcreatefullc:\\ifm  查看详情

kubernetes重新生成证书,重新生成配置文件(代码片段)

生成证书备份原来的证书cp-ra/etc/kubernetes/pki,.bakls/etc/kubernetes/帮助信息kubeadminitphasecerts--helpThiscommandisnotmeanttoberunonitsown.Seelistofavailablesubcommands.Usage:kubeadminitphasecerts[flags]kubeadmini 查看详情

生成xml文件的(代码片段)

生成XML文件importsysclassBuildNewXML():#自定义建立XML文件类def__init__(self,filename=None):self.filename=filenameself.__get_f=None#自定义隐含属性(类内部使用)defopenfile(self):#自定义打开xml类函数openfileifself.filename==None:print(‘ 查看详情

随机生成文件名称(代码片段)

fromfakerimportFakerrn=lambdaftype:f"Faker().file_name(extension=ftype):>012"fname=rn("jpg")  查看详情

java实现大文件切割并生成多个文件(代码片段)

话不多说,直接上代码importjava.io.*;/****分割大文件*(*SQL文件太大(insert),第三方工具无法一次性读取,进行分割*生成一个一个文件*)*/publicclassSplitFileUtil//使用示例publicstaticvoidmain(String[]args)//目标文件StringtargetFile="F:\\logs\\ins... 查看详情

php使用php生成xml文件(代码片段)

查看详情

sh为文件生成sha1(代码片段)

查看详情

sh为https生成.pem文件(代码片段)

查看详情