<?php /*****连接数据库 start*******/ $dbhost = "localhost"; $username = "root"; $userpass = "root"; $dbdatabase = "eoews"; $db_con = mysqli_connect($dbhost,$username,$userpass) or die("Unable to connect to the MySQL!"); //选择一个需要操作的数据库 mysqli_select_db($db_con,$dbdatabase); /***********连接数据库****end******/ $page_size = 10000; //每页条数 //1w个地址生成一个子地图,判断需要生成几个? $countQuery = mysqli_query($db_con,"select count(id) from apps where status = 1 "); $count = implode(',' , mysqli_fetch_row($countQuery)); $page_count = ceil($count/$page_size); //分几个文件 baidu_create_index($page_count); baidu_create_child($db_con,$page_count,$page_size); //百度生成主sitemap function baidu_create_index($page_count) { $content = "<?xml version="1.0" encoding="utf-8"?>"; $content .= "<sitemapindex>"; for($i=1;$i<=$page_count;$i++) { $content .="<sitemap>"; $content .= "<loc> http://test.demo.cn/sitemap/sitemap$i.xml</loc>"; $content .= "<lastmod>".date('Y-m-d')."</lastmod>"; $content .= "</sitemap>"; } $content .= "</sitemapindex>"; file_put_contents("sitemap.xml",$content); } //百度生成子sitemap function baidu_create_child($db_con,$page_count,$page_size) { for($i=0;$i<$page_count;$i++) { $count = $i * $page_size; $result = mysqli_query($db_con,"SELECT id,updated_time FROM apps ORDER BY updated_time desc limit $count,$page_size"); //提取数据 if($result){ $str = '<?xml version="1.0" encoding="utf-8"?>'; $str .= '<urlset>'; while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) { $str .= '<url>'; $str .= "<loc>http://test.eoews.cn/soft/{$row["id"]}.html</loc>"; $str .= "<lastmod>" . date('Y-m-d',strtotime($row["updated_time"])) . "</lastmod>"; $str .= "<changefreq>daily</changefreq>"; $str .= "<priority>0.9</priority>"; $str .= '</url>'; } $str .= '</urlset>'; file_put_contents('sitemap/sitemap'.($i+1).".xml" ,$str); }else{ die("fetch data failed!"); } mysqli_free_result($result); } }
用的是原生写的。没有用到框架 要是用框架的话 应该会方便很多,至少在Mysql 上不会这么复杂