最近老是遇到很多用不常见的程序搭建网站的,在做SEO的时候发现很多功能都没有,比如网站地图,网站地图对网站是很有用的,方便用户查找到需要资料的同时还能让蜘蛛爬取页面更为便携,从而增加收录,下边这个生成sitemap.xml地图文件的PHP代码就是让你在网站后台没有sitemap地图功能的时候使用,(亲测可用):

使用方法:在网站根目录新建一个sitemap.php文件,把以下代码复制进去,然后浏览器访问http://域名/sitemap.php,就OK了。

上代码:

<?php
/**
* 生成sitemap.xml文件
*/
$WebRoot = "http://www.52sharew.com/";//这里改成你的域名就好,其他不用改

$XMLFile = "sitemap.xml";

$FilterDir = "+|admin|example|";

$IndexFileExt = "+|HTML|";

$XMLText = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.google.com/schemas/sitemap/0.84\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd\">";

$XMLEndText = "</urlset>";
echo "开始构建文件XML索引...";
DealFP(".");
$XMLText .= $XMLEndText;
makeFile($XMLFile,$XMLText);
echo "ok!<br><br>";
$url = $WebRoot.$XMLFile;
echo "<a href=".$url.">打开</a>:".$url;
//公用函数库:
//新建文件
function makeFile($fileName, $text){
$fp = fopen($fileName, "w+");
fwrite($fp, $text);
fclose($fp);
}
/**
* 将指定内容添加到XML中
* $f 含相对路径的文件名称
* $dt 日期时间型
*/
function addToXML($f, $dt){
$s = "<url><loc>".$GLOBALS["WebRoot"].$f."</loc>\n<lastmod>".$dt."</lastmod>\n<changefreq>daily</changefreq>\n<priority>1</priority></url>\n";


$GLOBALS["XMLText"] .= $s;
}
/**
* 遍历指定的目录以及子目录,将符合条件的文件加入XML
* $p 指定的目录
*/
function DealFP($p){
$FilterDir = $GLOBALS["FilterDir"];
$IndexFileExt = $GLOBALS["IndexFileExt"];

$handle=opendir($p);
if ($p==".") $path = "";
else $path = $p."/";
while ($file = readdir($handle))
{
    $d = filetype($path.$file);
    if ((($d=='file')||($d=='dir'))&&($file!='.')&&($file!='..'))
    {
        $pf = $path.$file;
        //echo "[".$d."]".$pf."<br>";
        if ($d=='dir')
        {
          if (!(strpos($FilterDir, "|".$pf."|")))
          {
            DealFP($pf);
          }
        }else{
          $ext = "|".strtolower(substr($file, strrpos($file, ".")+1))."|";
          
          if (strpos($IndexFileExt, $ext))
          {
            $d = filemtime($pf);
            $dt = date("Y-m-d",$d)."T".date("H:i:s",$d)."+00:00";
            addToXML($pf, $dt);
          }
        }
    }
}
closedir($handle); 
}
?>

发表回复