php封装一个简单的网站地图生成类

方文锋  2026-10-01 12:14:46  2  首页学习PHP

使用PHP写一个简单的网站地图生成的类,代码如下:



<?php

namespace app\home\model;

/**
 * 网站地图
 * Class sitemap
 * @package app\home\model
 */
class sitemap
{
    private $url_data = [];
    private $baseUrl = ''; //网站域名

    public function y_string($str = '')
    {
        return !in_array($str, array('', null, false), true) && (is_string($str) || is_numeric($str));
    }

    public function is_ssl()
    {
        if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
            return true;
        } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
            return true;
        }
        return false;
    }

    public function ok_array($arr = [])
    {
        return is_array($arr) && count($arr) > 0;
    }

    /**
     * 插入数据
     * @param string $loc 网址链接
     * @param string $priority 权重
     * @param string $changefreq 变更时间
     * @return array
     */
    public function insert($loc = '/', $priority = '0.8', $changefreq = 'weekly')
    {
        self::y_string($this->baseUrl) || $this->set_baseUrl();
        $loc = rtrim($this->baseUrl, '/') . '/' . ltrim($loc, '/');
        $data = array('loc' => htmlspecialchars($loc), 'priority' => $priority, 'changefreq' => $changefreq);
        $this->url_data[] = $data;
        return $data;
    }

    /**
     * 创建XML文本字符
     * @return string|boolean
     */
    public function createXML()
    {
        if (!is_array($this->url_data) || (is_array($this->url_data) && count($this->url_data) < 1)) {
            return false;
        }
        $url_xml = '';
        foreach ($this->url_data as $index => $data) {
            $url_xml .= "<url><loc>{$data['loc']}</loc><changefreq>{$data['changefreq']}</changefreq><priority>{$data['priority']}</priority></url>\n";
        }
        $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n" . $url_xml . '</urlset>';
        return $xml;
    }

    public function set_baseUrl($url = '')
    {
        $is_ssl = self::is_ssl() ? 'https://' : 'http://';
        self::y_string($url) || ($url = $is_ssl . $_SERVER['HTTP_HOST']);
        $this->baseUrl = $url;
        return $this;
    }

    public function get_url_data()
    {
        return $this->url_data;
    }
} 


使用方法例如:



<?php
$sitemap = new \app\home\model\sitemap();
$sitemap->insert('/index');
$sitemap->insert('/about');
header("Content-Type: application/xml; charset=utf-8");
echo $sitemap->createXML();