`

Thinkphp二级网站地图XML生成的方法[图解]

阅读更多
在admin项目的Tpl目录下default目录里的SiteMap_index.html文件:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="../Public/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" charset="utf-8" src="__PUBLIC__/js/artDialog/artDialog.min.js"></script>
<title>网站地图生成XML</title>
</head>
<body>
<script language="javascript">
function clicktodosome(type){
if(!window.confirm('确定要生成网站地图吗?')){
  return; 
}
var testDialog;
testDialog = art.dialog({
  lock: false,
  title:'',
  id:'loaddialog',
  content:'<font color="#ff0000">正在生成网站地图中...</font>',
  width:220
});
//url="{:U('indexrightlist')}";
switch(type){
  case 1:
   var url="{:U('buildingXML')}"; 
   break;
  case 2:
   var url="{:U('newsXML')}";
   break;
}

$.get(url,null,function(data){
  //$("#con").append(data);
  testDialog.close();
  $("#con").html(data);
});
}
function showpage(url){
var testDialog;
testDialog = art.dialog({
  lock: false,
  title:'',
  id:'loaddialog',
  content:'<font color="#ff0000">正在加载中...</font>',
  width:220
});
$.get(url,null,function(data){
  //$("#con").append(data);
  testDialog.close();
  $("#con").html(data);
});
}
</script>
<style type="text/css">
#con ul li{ line-height:22px;}
.d_page { padding-top:10px;}
</style>
<div class="right_box">
  <div class="dqwz">
    <div class="left l17"><strong class="f14">网站地图管理</strong><span class="all366C padl_13">&nbsp;</span></div>
    <div class="right all366C"></div>
  </div>
  <dl class="qbright w_100">
    <dd style="border:none;">
      <li style="font-size:15px;"><strong>生成<span style="color:#F00;">楼盘</span>网站地图:</strong>  <input name="save" type="submit" class="agin tj cur" value="生 成" onClick="clicktodosome(1)"/></li>
    </dd>
  </dl>
  
  
  <dl class="qbright w_100">
    <dd style="border:none;">
      <li style="font-size:15px;"><strong>生成<span style="color:#F00;">资讯</span>网站地图:</strong>  <input name="save" type="submit" class="agin tj cur" value="生 成" onClick="clicktodosome(2)"/></li>
    </dd>
  </dl>
  
    <div id="con"></div>
  <div class="clear"></div>
</div>
<br><br>
</body>
</html>



在admin项目的Action目录下SiteMapAction.class.php文件:

<?php

/**
* @author xiaohu
* @copyright 2010
*/

class SiteMapAction extends AdminAction {
public $page = '';

    public function _initialize() {
  include(BASE_PATH."Public/Lang/".C("DEFAULT_LANG")."/citys.php"); //获取城市的数组
  $this->assign("cityArr", $cityArr);
    }

//生成楼盘地图
public function buildingXML(){
  include(BASE_PATH."Public/Lang/".C("DEFAULT_LANG")."/citys.php"); //获取城市的数组
  $fnArr = createXML('building');
  //分页 
  $fnArr = $this->array_page($fnArr);
  $html = '<ul>';
  foreach($fnArr as $key=>$val){
   if($key == 0){
    $html .= '<li>生成<font color="#FF0000">全站</font>楼盘总地图成功:<a href="'.WWWURL.'/'.$val.'" target="_blank">'.WWWURL.'/'.$val.'</a></li>';
   }else{
    $city = preg_replace('/[^0-9]/i','',$val);
    $html .= '<li>生成<font color="#FF0000">'.$cityArr[$city].'</font>楼盘地图成功:<a href="'.WWWURL.'/'.$val.'" target="_blank">'.WWWURL.'/'.$val.'</a></li>';
   }
  }
  $html .= '</ul><div class="d_page">'.$this->page.'</div>';
  exit($html);
}

//生成资讯地图
public function newsXML(){
  $categoryArr = $this->categoryArr();
  $fnArr = createXML('news');
  //分页 
  $fnArr = $this->array_page($fnArr);
  $html = '<ul>';
  foreach($fnArr as $key=>$val){
   if($key == 0){
    $html .= '<li>生成<font color="#FF0000">全站</font>资讯总地图成功:<a href="'.WWWURL.'/'.$val.'" target="_blank">'.WWWURL.'/'.$val.'</a></li>';
   }else{
    $categoryId = preg_replace('/[^0-9]/i','',$val);
    $html .= '<li>生成<font color="#FF0000">'.$categoryArr[$categoryId].'</font>资讯地图成功:<a href="'.WWWURL.'/'.$val.'" target="_blank">'.WWWURL.'/'.$val.'</a></li>';
   }
  }
  $html .= '</ul><div class="d_page">'.$this->page.'</div>';
  exit($html);
}

function categoryArr(){
  //一级分类
  $categoryM=M("NewsCategory");
  $categoryIdList=$categoryM->field("id,title")->where("level=1")->select();
  foreach($categoryIdList as $key=>$val) {
   $NewsCategoryArr[$val['id']] = $val['title']; 
  } 
  return $NewsCategoryArr; 
}

//数组分页
/**
* array  $array 数组
* integer $showCount 每页的记录数
*------------------------------
* return array 返回数组
*/
function array_page($array,$listRows = 12,$showCount = 4){
  $p = C('VAR_PAGE');
  $url  =  $_SERVER['REQUEST_URI']."/".$p."/";
  $page  = !empty($_GET[C('VAR_PAGE')])?$_GET[C('VAR_PAGE')]:1;
        $upRow   = $page-1;
        $downRow = $page+1;  
  $linkPage = "";
  $totalPage = (int)count($array);
  $pagetotal = ceil($totalPage/$listRows); //总页数
  if($page <= ceil(($showCount)/2)){
   $minpg = 1;
   $maxpg = $showCount+1;
   if($maxpg >= $pagetotal) $maxpg = $pagetotal + 1;
  }elseif($page > ceil(($showCount)/2) && $page < ($pagetotal - ceil($showCount/2))){
   $minpg = $page - ceil(($showCount)/2) + 1;
   $maxpg = $page + ceil(($showCount)/2) + 1;
   if($maxpg >= $pagetotal) $maxpg = $pagetotal;
  }elseif($page >=$pagetotal - ceil(($showCount)/2)){
   $minpg = $pagetotal - ($showCount-1);
   if($minpg == 1) $minpg = 2;
   $maxpg = $pagetotal + 1;
  }  
  
  $linkPage .= " ".$totalPage." 条记录 ".$page."/".$pagetotal." 页 ";
  
  if($pagetotal == 1){
   $linkPage .= "&nbsp;<span class='current'>1</span>&nbsp;";
  }else{
   if($page > 1){
    $linkPage .= "&nbsp;&nbsp;<a href='javascript:void(0)' onClick=\"showpage('".$url."1');\">第一页</a>";
    $linkPage .= "&nbsp;&nbsp;<a href='javascript:void(0)' onClick=\"showpage('".$url.$upRow."');\">上一页</a>";
   }
   for($i = $minpg; $i < $maxpg; $i++){
    if($page == $i){
     $linkPage .= "&nbsp;&nbsp;<span class='current'><font color=\"#FF0000\">". $i ."</font></span>";
    }else{
     $linkPage .= "&nbsp;&nbsp;<a href='javascript:void(0)' onClick=\"showpage('".$url.$i."');\">$i</a>";
    }
   }
   if($page < $pagetotal){
    $linkPage .= "&nbsp;&nbsp;<a href='javascript:void(0)' onClick=\"showpage('".$url.$downRow."');\">下一页</a>";
    $linkPage .= "&nbsp;&nbsp;<a href='javascript:void(0)' onClick=\"showpage('".$url.$pagetotal."');\">最后一页</a>";
   }
  }   
  
  if($listRows < $totalPage) {
   if($page <= 1 || empty($page)) {
    $page = 0;
   } else {
    $page = intval($page) - 1;
   }
   $array = array_slice($array,$page*$listRows,$listRows,true);
  }
  $this->page = $linkPage;
  if(1 == $pagetotal) $this->page = '';
  return $array;  
}
}
?>



在admin项目的Common目录下common.php文件:

/**
*   生成xml文件
* string $fn 要生成的文件名(包括扩展名)
* string $type 标识是楼盘还是资讯等其他的
*            building  --  楼盘
*            news      --  新闻资讯
*   $integer $isFlag 是否全部生成
*   $integer $category  分类或城市的ID
*/
function createXML($type,$isFlag=1,$category=0){
if($type == 'building'){  //楼盘
  $model = M('BuildingBase');
  $list = $model->field('city as Numbers')->where('status >= 5')->order('city asc')->group('city')->findAll();
  $url = WWWURL;
}else if($type == 'news'){  //资讯
  $model = M('News');
  $list = $model->field('categoryId as Numbers')->where('status >= 5')->order('categoryId asc')->group('categoryId')->findAll();
  $url = WWWURL;
}
$fn = 'sitemap.xml';
$fp = "./xml/";
//生成一级全部
$isExist = searchFile($fp,$fn);
if($isExist == 'no'){ //没找到sitemap.xml文件
  modeXMl($list,$url,$type,$isExist,$fp,$fn);
}else if($isExist == 'yes'){ //找到sitemap.xml文件且只修改相应的部分
  $doc = new DOMDocument();
  $doc->load( './xml/'.$fn );
  $root = $doc -> documentElement;
  $books = $doc->getElementsByTagName( "sitemap" );
  if($isFlag == 1){
   $count_book = $books->length;
   for($i = 0; $i < $count_book; $i++){
    if($books->item(0)->getAttribute('name') == $type){
     $book = $books->item(0);
     $root->removeChild($book);
    }
   }
   $doc->save('./xml/'.$fn);
   modeXMl($list,$url,$type,$isExist,$fp,$fn);
  }else if($isFlag == 0){
   foreach( $books as $book ){
    if($book->getAttribute('id') == $category && $book->getAttribute('name') == $type){
     $book->getElementsByTagName( "lastmod" )->item(0)->nodeValue=date('Y-m-d',time());
    }
   }
   $doc->save('./xml/'.$fn);
  }
}

$fnArr = array();
$fnArr[0] = $fn;
//生成二级xml
if($isFlag == 1){  //生成二级全部
  foreach($list as $key=>$val){
   $fnArr[$key+1] = createSubXML($model,$val['Numbers'],$type,$fp);
  }
}else if($isFlag == 0){ //生成二级的单个
  $fnArr[0] = createSubXML($model,$category,$type,$fp);
  return;
}
return $fnArr;
}

/**
*   生成分类xml
*   string $model 数据库模型
*   integer $category 分类或城市的ID
* string $type 标识是楼盘还是资讯等其他的
*            building  --  楼盘
*            news      --  新闻资讯
*/
function createSubXML($model,$category,$type,$fp){
$fn = '';
if($type == 'building'){  //楼盘
  $subList = $model->field('id as Numbers')->where('status >= 5 and city='.$category)->order('id desc')->findAll();
  $url = WWWURL . "/building/";
  $extension = '';
}else if($type == 'news'){  //资讯
  $subList = $model->field('id as Numbers')->where('status >= 5 and categoryId='.$category)->order('id desc')->findAll();
  $url = NEWSURL . "/article/";
  $extension = '.html';
}
$fn = $type.$category.".xml";
modeSubXMl($subList,$url,$type,$extension,$fp,$fn);
return $fn;
}

/**
*   创建文件夹
* string $path 文件路径(不包括文件名)
*/
function _mkdirm($path)
{
if (!file_exists($path))
{
  _mkdirm(dirname($path));
  mkdir($path, 0777);
}
}

/**
*   写入文件
* string $fp 文件路径(不包括文件名)
*   string $fn 文件名(包括扩展名)
*   string $content 写入的内容
*/
function writeFile($fp,$fn,$content){
if(!empty($fp)) _mkdirm($fp);
$fp .= $fn;
$fpen = fopen($fp, "w");
fwrite($fpen, $content);
fclose($fpen); 
}

//检查上传文件的目录里是否已存在同名的上传文件
function searchFile($path,$file){
$file_array=array(); //存放文件名数组
$folder_array=array(); //存放目录名数组
$all_array=array(); //存放全部路径的数组

if(is_dir($path)){  //检查文件目录是否存在
  $H = @ opendir($path);
  while(false !== ($_file=readdir($H))){
   //检索目录
   if(is_dir($path."/".$_file) && $_file != "." && $_file!=".." && $_file!=="Thumbs.db"){
    if(eregi('/'.$file,'/'.$_file)){
     array_push($folder_array,$path."/".$_file);
    }
    searchFile($path."/".$_file,$file);
   //检索文件
   }elseif(is_file($path."/".$_file) && $_file!="." && $_file!=".." && $_file!=="Thumbs.db"){
    //$_file = auto_charset($_file,'utf-8','gbk');
    if(eregi('/'.$file,'/'.$_file)){
     array_push($file_array,$path."/".$_file);
     return 'yes'; //文件存在
    }
   }
  }
  //$this->all_array["folder"]=$this->folder_array;
  //$this->all_array["file"]=$this->file_array;
  closedir($H);
  return 'no'; //不存在
}elseif(is_file($path)){
  if(eregi($file,$path)){
   //$this->all_array["file"]=$path;
   return 'yes'; //文件存在
  } else {
   return 'no'; //文件不存在
  }
}else{
  return 'no'; //文件不存在
}
}


/**
*   xml第一级模板生成
* array $array 需要生成的数组
*   string $url 生成后里面的url链接
* string $type 标识是楼盘还是资讯等其他的
*            building  --  楼盘
*            news      --  新闻资讯
*   string $fp  文件路径(不包括文件名)
*   string $fn  文件名称(包括扩展名).
*/
function modeXMl($array,$url,$type,$isExist,$fp = './xml/',$fn = 'sitemap.xml'){
if($isExist == 'no'){
  $doc = new DOMDocument('1.0', 'utf-8');  // 声明版本和编码
  $doc -> formatOutput = true;  //格式XML输出
  $sitemapindex = $doc->createElement('sitemapindex');  //创建一个标签
  $xmlns     = $doc->createAttribute('xmlns');  //创建一个属性
  $xmlnsVal   = $doc->createTextNode('http://www.google.com/schemas/sitemap/0.9');
  $xmlns    -> appendChild($xmlnsVal);   //继承属性
  $sitemapindex -> appendChild($xmlns);  //继承属性内容
}else if($isExist == 'yes'){
  $doc = new DOMDocument();
  $doc->load( $fp.$fn );
  $sitemapindex = $doc->getElementsByTagName( "sitemapindex" )->item(0);
}

foreach($array as $key=>$val){
  $sitemap   = $doc->createElement('sitemap');  //创建一个标签
  $name     = $doc->createAttribute('name');  //创建一个属性
  $nameVal   = $doc->createTextNode($type);  //设置属性内容
  $name    -> appendChild($nameVal);  //继承属性
  $id     = $doc->createAttribute('id');  //创建一个属性
  $idVal       = $doc->createTextNode($val['Numbers']);  //设置属性内容
  $id        -> appendChild($idVal);  //继承属性
  $sitemap      -> appendChild($name);  //继承属性内容
  $sitemap   -> appendChild($id);  //继承属性内容
  
  $loc       = $doc->createElement('loc');  //创建一个标签
  $locContent   = $doc->createTextNode($url."/".$type.$val['Numbers'].".xml");  //设置标签内容
  $loc    -> appendChild($locContent); //继承标签内容
  
  $lastmod   = $doc->createElement('lastmod');  //创建一个标签
  $lastmodCon   = $doc->createTextNode(date('Y-m-d',time()));  //设置标签内容
  $lastmod   -> appendChild($lastmodCon); //继承标签内容
  
  $sitemap   -> appendChild($loc);  //继承子类
  $sitemap   -> appendChild($lastmod);  //继承子类
  $sitemapindex -> appendChild($sitemap); //继承子类
}
if($isExist == 'no'){
  $doc              -> appendChild($sitemapindex); //继承子类
}

if(!empty($fp)) _mkdirm($fp);
$doc              -> save($fp.$fn);                  // 生成保存为XML
}

/**
*   xml第二级模板生成
* array $array 需要生成的数组
*   string $url 生成后里面的url链接
* string $type 标识是楼盘还是资讯等其他的
*            building  --  楼盘
*            news      --  新闻资讯
*   string $fp  文件路径(不包括文件名)
*   string $fn  文件名称(包括扩展名)
*/
function modeSubXMl($array,$url,$type,$extension = '',$fp = './xml/',$fn = 'sitemap.xml'){
$doc = new DOMDocument('1.0', 'utf-8');  // 声明版本和编码
$doc -> formatOutput = true;  //格式XML输出

$urlset       = $doc->createElement('urlset');  //创建一个标签
$xmlns     = $doc->createAttribute('xmlns');  //创建一个属性
$xmlnsVal   = $doc->createTextNode('http://www.google.com/schemas/sitemap/0.9');
$xmlns    -> appendChild($xmlnsVal);   //继承属性
$urlset       -> appendChild($xmlns);  //继承属性内容

for($i = 1; $i <= 3; $i++){
  switch($i){
   case 1:
    $tUrl = WWWURL;
    break;
  }
  $urlXML       = $doc->createElement('url');  //创建一个标签
  
  $loc       = $doc->createElement('loc');  //创建一个标签
  $locContent   = $doc->createTextNode($tUrl);  //设置标签内容
  $loc    -> appendChild($locContent); //继承标签内容
  
  $urlXML       -> appendChild($loc);  //继承子类
  $urlXML       -> appendChild($lastmod);  //继承子类
  $urlset       -> appendChild($urlXML); //继承子类
} 

foreach($array as $key=>$val){
  $urlXML       = $doc->createElement('url');  //创建一个标签
  $name     = $doc->createAttribute('name');  //创建一个属性
  $nameVal   = $doc->createTextNode($type);  //设置属性内容
  $name    -> appendChild($nameVal);  //继承属性
  $id     = $doc->createAttribute('id');  //创建一个属性
  $idVal       = $doc->createTextNode($val['Numbers']);  //设置属性内容
  $id        -> appendChild($idVal);  //继承属性
  $urlXML       -> appendChild($name);  //继承属性内容
  $urlXML       -> appendChild($id);  //继承属性内容  
  
  $loc       = $doc->createElement('loc');  //创建一个标签
  $locContent   = $doc->createTextNode($url.$val['Numbers'].$extension);  //设置标签内容
  $loc    -> appendChild($locContent); //继承标签内容
  
  $urlXML       -> appendChild($loc);  //继承子类
  $urlXML       -> appendChild($lastmod);  //继承子类
  $urlset       -> appendChild($urlXML); //继承子类
}
$doc              -> appendChild($urlset); //继承子类

if(!empty($fp)) _mkdirm($fp);
$doc              -> save($fp.$fn);                  // 生成保存为XML
}

 

 

1
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics