PHP实现生成sitemap文件功能

作者:IT技术圈子 浏览量:428   发表于 2023-10-01 00:03 标签:

   sitemap文件一般可用于SEO优化,有利于搜索引擎收录网站地址。360搜索、百度搜索均支持通过sitemap文件的形式提交网站url。

随着时间的推移,网站地址会越来越多,手动提交的效率会比较低,那么通过sitemap形式,可以解放双手。PHP中也可以实现sitemap文件的生成

实现生成sitemap文件代码如下

/**
     * 生成sitemap文件
     * @return void
     * @throws \DOMException
     */
    public function actionSiteMap()
    {
        // 创建一个DOMDocument对象
        $dom = new \DOMDocument('1.0','utf-8');
        // 创建根节点
        $dom ->formatOutput = true;

        //设置urlset
        $urlset = $dom ->createElement("urlset");

        //xmlns
        $xmlns = $dom ->createAttribute('xmlns');
        $xmlnsvalue = $dom ->createTextNode("http://www.sitemaps.org/schemas/sitemap/0.9");
        $xmlns -> appendChild($xmlnsvalue);
        $urlset ->appendChild($xmlns);

        //xmlns:mobile
        $xmlns_mobile = $dom ->createAttribute('xmlns:mobile');
        $xmlns_mobilevalue = $dom ->createTextNode("http://www.baidu.com/schemas/sitemap-mobile/1/");
        $xmlns_mobile -> appendChild($xmlns_mobilevalue);
        $urlset ->appendChild($xmlns_mobile);
        $dom ->appendChild($urlset);


        //要提交百度的地址
        /** @var ArticleEntity[] $models */
        $models = ArticleEntity::find()->where([
            'status' => StatusEnum::ON
        ])->all();

        foreach ($models as $model) {
            // 建立根下子节点track
            $track = $dom ->createElement("url");
            $urlset ->appendChild($track);
            // 建立track节点下元素
            $loc = $dom ->createElement("loc");
            $track ->appendChild($loc);

            $priority = $dom ->createElement("priority");
            $track ->appendChild($priority);

            $lastmod = $dom ->createElement("lastmod");
            $track ->appendChild($lastmod);

            $changefreq = $dom ->createElement("changefreq");
            $track ->appendChild($changefreq);

            $mobile_mobile = $dom ->createElement("mobile:mobile");

            $type = $dom ->createAttribute('type');
            $typevalue = $dom ->createTextNode("pc,mobile");
            $type -> appendChild($typevalue);
            $mobile_mobile ->appendChild($type);
            $track ->appendChild($mobile_mobile);


            $url = "https://www.befun.ink/detail/{$model->id}.html";
            $text = $dom ->createTextNode($url);
            $loc ->appendChild($text);

            $text = $dom ->createTextNode($model->create_time);
            $lastmod ->appendChild($text);
            $text = $dom ->createTextNode("weekly");
            $changefreq ->appendChild($text);
            $text = $dom ->createTextNode(1);
            $priority ->appendChild($text);
        }

        $dom->save("./fun-sitemap.xml"); //保存路径 绝对路径
    }