浏览文章
文章信息
PHP实时自动生成sitemap.xml|PHP auto create sitemap.xml
20385
一、目录层次:
文件下载地址:https://bbs.aiweline.com/attach-download-41.htm
附件解压密码:bbs.aiweline.com
项目根目录:
----conf.php---------------[文件] ----AutoSiteMap.php--------[文件] ----M----------------------[目录] |--Db------------------[目录] |--Mdb.php----------[文件]
扩展使用教程:
如果不想在AutoSiteMap.php中创建,可另建PHP文件,例如siteMaper.php,调用AutoSiteMap.php即可
示例:siteMaper.php,此时为siteMaper.php设置crontab定时任务就可以实现自动定时生成sitemap.xml文件
Crontab设置教程:https://bbs.aiweline.com/thread-68.htm
# 引入AutoSiteMap.php include dirname(__FILE__) . '/AutoSiteMap.php'; # 实例化 $sitemap = new SiteMap(); $sitemapxml = $sitemap ->setSite('bbs.aiweline.com') ->setTable('thread') ->setFormatOutput(true) ->setLocFormatStr('https://bbs.aiweline.com/?thread-{tid}.htm')#数据库字段,一般是id ->setReplaceStr('tid')#数据库字段,一般是id ->setChangefreq('always') ->setPriority('0.8') ->createSiteMap(); $sitemapxml->save('sitemap.xml');
二、文件内容:
1、conf.php
<?php /** * 文件信息 * * 工具:PhpStorm * 作者:邹万才 * 网名:秋风雁飞 * 日期:2019-7-19 * 时间:下午 11:38 */ return array( 'db' => array( 'mysql' => array( 'master' => array( 'host' => '127.0.0.1', 'user' => 'user', 'password' => 'password', 'name' => 'dbname', 'tablepre' => 'dev_', 'charset' => 'utf8' ) ) ) );
1、M\Db\Mdb.php
<?php /** * Created by PhpStorm. * User: 秋枫雁飞 * Date: 2019/6/19 * Time: 10:06 */ namespace M\Db; use mysqli; class Mdb { private static $_instance = null;//该类中的唯一一个实例 protected $env = null; protected $tablepre = null; protected $link = null; private $table = ''; private $where = ''; private $limit = ''; private $sql = ''; protected $query_data = null; /** * Mdb constructor. * @param DeploymentConfig $config * @param Debug $debug */ public function __construct() { $this->env = $_SERVER['conf']; $mysql_conf = isset($this->env['db']['mysql']['master'])?$this->env['db']['mysql']['master']:die('DB conf lost.'); $conn = new mysqli($mysql_conf['host'], $mysql_conf['user'],$mysql_conf['password'], $mysql_conf['name']); /*if (!$conn->set_charset('utf8')) { printf("Error loading character set utf8: %s\n", $conn->error); exit(); }*/ if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } else { $this->tablepre = $mysql_conf['tablepre']; $conn->query($mysql_conf['charset']); $this->link = $conn; } unset($_SERVER['conf']); } /** *禁止通过复制的方式实例化该类 */ private function __clone() { } /** * 检查实例,如果存在继续使用,不存在重新实例化 * @return Mdb|null */ /*public static function Db() { if (self::$_instance == null) { self::$_instance = new self(); } return self::$_instance; }*/ /** * 连接信息 * @return mixed|null */ public function status() { return $this->env; } public function getLink() { return $this->link; } public function query($sql) { $this->sql = $sql; $result = $this->link->query($sql) or trigger_error("Query Failed! SQL: $sql - Error: " . $this->link->error, E_USER_ERROR);; $data = is_bool($result) ? $result : $result->fetch_all(MYSQLI_ASSOC); $this->query_data = $data; return $this; } public function table($table) { if(!strpos($this->tablepre,$table)){ $table = $this->tablepre.$table; } $this->table = " `{$table}` "; return $this; } /********************** helper start *********************** * @param $k * @param $item * @param $data * @return string * @throws \Exception */ protected function parseInStr($k, $item, $data) { $not_in_str = ' '; if (is_string($item)) { $item__fields_arr = explode(',', $item); foreach ($item__fields_arr as $item_k => $item_fields) { $not_in_str .= '"' . $item_fields . '",'; } } else if (is_array($item)) { foreach ($item as $item_k => $item_fields) { $not_in_str .= '"' . $item_fields . '",'; } } else { $this->addError($data); } return ' '.$k . ' (' . rtrim($not_in_str, ',') . ')'; } /********************** helper end ************************/ /** * @param string $where * @return $this * @throws \Exception */ public function where($where = '') { $where_str = ' WHERE '; if (is_array($where)) { $where_str_tmp = ''; foreach ($where as $key => $value) { $tmp_str = ' `' . $key . '`'; if (is_array($value)) { switch (count($value)) { case 1: if (isset($value[0])) { $tmp_str .= '=' . (is_string($value[0]) ? '"' . $value[0] . '"' : $value[0]); } else { foreach ($value as $k => $item) { $tmp = ''; switch (strtoupper($k)) { case 'NOT IN': $tmp .= $this->parseInStr($k, $item, $where); break; case 'IN': $tmp .= $this->parseInStr($k, $item, $where); break; default: if ($k == 0) { $tmp .= ' ' . $item; } else { $tmp .= ' ' . (is_string($item) ? '"' . $item . '"' : $item); } break; } $tmp_str .= $tmp; } } break; case 2: foreach ($value as $k => $item) { $tmp = ' '; switch (strtoupper($k)) { case 'NOT IN': $tmp .= $this->parseInStr($k, $item, $where); break; case 'IN': $tmp .= $this->parseInStr($k, $item, $where); break; default: if ($k == 0) { $tmp .= ' ' . $item; } else { $tmp .= ' ' . (is_string($item) ? '"' . $item . '"' : $item); } break; } $tmp_str .= $tmp; } break; case 3: switch ($value[1]) { case 'OR': $tmp_str .= '=' . (is_string($value[0]) ? '"' . $value[0] . '"' : $value[0]) . ' ' . $value[1] . ' `' . $key . '`' . '=' . (is_string($value[2]) ? '"' . $value[2] . '"' : $value[2]); break; case 'or': $tmp_str .= '=' . (is_string($value[0]) ? '"' . $value[0] . '"' : $value[0]) . ' ' . $value[1] . ' `' . $key . '`' . '=' . (is_string($value[2]) ? '"' . $value[2] . '"' : $value[2]); break; default: $this->addError($where); } } } else { $tmp_str .= '=' . (is_string($value) ? '"' . $value . '"' : $value); } $where_str_tmp .= $tmp_str . ' AND '; } $where_str .= rtrim($where_str_tmp, 'AND '); } else { $where_str .= $where; } $this->where = $where_str; return $this; } public function limit($start, $end = '') { if ($end) { $this->limit = " LIMIT $start,$end"; } else { $this->limit = " LIMIT $start"; } return $this; } public function delete() { $this->sql = "DELETE FROM {$this->table} {$this->where}"; $this->query($this->sql); return $this; } public function fetch($flag = false) { if ($flag) { $this->buildSql(); } return $this->query_data; } public function select($fields = '*') { $this->sql = "SELECT $fields FROM {$this->table} {$this->where} {$this->limit}"; $this->query($this->sql); return $this; } public function find() { $result = $this->link->query($this->sql); return is_bool($result) ? $result : $result->fetch_array(MYSQLI_ASSOC); } public function insert($data) { if (is_array($data)) { $keys = '('; $values = '('; foreach ($data as $key => $value) { $keys .= '`' . $key . '`,'; $values .= (is_string($value) ? "'$value'" : $value) . ','; } $keys = rtrim($keys, ','); $keys .= ') '; $values = rtrim($values, ','); $values .= ') '; $data = $keys . ' VALUES ' . $values; } $this->sql = "INSERT INTO {$this->table} {$data}"; $this->query($this->sql); return $this; } public function update($data) { if (is_array($data)) { $update_str = ''; foreach ($data as $key => $value) { $update_str .= "`$key`=" . (is_string($value) ? "'$value'," : "$value,"); } $update_str = rtrim($update_str, ','); $data = $update_str; } $this->sql = "UPDATE {$this->table} SET {$data} {$this->where}"; $this->query($this->sql); return $this; } public function begin_transaction() { // $this->link->begin_transaction(MYSQLI_TRANS_START_READ_ONLY); $this->link->autocommit(false); } public function rollBack() { $this->link->rollback(); } public function commit() { $this->link->commit(); $this->link->autocommit(true); } public function close() { mysqli_close($this->link); } public function buildSql($flag = true) { if ($flag) { echo '<br><i style="color: red">' . $this->sql . '</i><br><br>'; } return $this->sql; } private function addError($data) { throw new \Exception('SQL:parse error!in where method the data is' . is_string($data) ? $data : 'Array:' . implode(',', $data)); } }
2、AutoSiteMap.php
<?php $_SERVER['conf'] = include dirname(__FILE__) . '/conf.php'; spl_autoload_register( /** * @param $name * @return bool */ function ($name) { $spacename_dir = substr($name, 0, strrpos($name, '\\')); $dir_path = dirname(__FILE__) . '/' . str_replace('\\', '/', $spacename_dir); $file_name = substr($name, strrpos($name, '\\'), strlen($name)); $file_path = $dir_path . str_replace('\\', '/', $file_name) . '.php'; #var_dump($file_path);die; if (file_exists($file_path)) { try { require_once $file_path; return true; } catch (\Exception $e) { throw new Exception("Unable to load $name." . $e->getMessage()); } } else { throw new Exception("Unable to load $name.File not exsit!"); } }); use M\Db\Mdb; /** * @property changefreq */ class SiteMap { protected $db = null; private $site = 'bbs.aiweline.com'; private $table = null; private $locFormatStr = 'https://bbs.aiweline.com/?thread-{id}.htm'; private $replace_str = 'id'; private $formatOutput = true; private $priority = 0.8; private $changefreq = 'daily'; private $saveFilePath = 'sitemap.xml'; public function __construct() { $this->db = new Mdb(); } /** * @param string $site * @return SiteMap */ public function setSite($site) { $this->site = $site; return $this; } /** */ protected function getThread() { return $this->db->table($this->table)->select()->fetch(); } /** * @param null $table * @return SiteMap */ public function setTable($table) { $this->table = $table; return $this; } function create() { return $this->createSiteMap()->save($this->saveFilePath); } protected function createSiteMap() { // 创建一个DOMDocument对象 $dom = new DOMDocument("1.0", "utf-8"); $dom->formatOutput = $this->formatOutput; //header("Content-Type: text/xml"); // 创建根节点 $root = $dom->createElement("urlset"); $root->setAttribute('xmlns','http://www.sitemaps.org/schemas/sitemap/0.9'); $root->setAttribute('xmlns:xsi','http://www.w3.org/2001/XMLSchema-instance'); $root->setAttribute('xsi:schemaLocation','http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'); $dom->appendChild($root); foreach ($this->getThread() as $value) { // 建立根下子节点track $track = $dom->createElement("url"); $root->appendChild($track); // 建立track节点下元素 $locFormatStr = $dom->createElement("loc"); $track->appendChild($locFormatStr); $priority = $dom->createElement("priority"); $track->appendChild($priority); $lastmod = $dom->createElement("lastmod"); $track->appendChild($lastmod); $changefreq = $dom->createElement("changefreq"); $track->appendChild($changefreq); // 赋值 # '{protocol}://{domain}/{id}.{Suffix}'; $tmp_url = $this->locFormatStr; $text = $dom->createTextNode(str_replace('{' . $this->replace_str . '}', $value[$this->replace_str], $tmp_url)); $locFormatStr->appendChild($text); $text = $dom->createTextNode($this->priority); $priority->appendChild($text); $date = date("Y-m-d", time()); $text = $dom->createTextNode($date); $lastmod->appendChild($text); $text = $dom->createTextNode($this->changefreq); $changefreq->appendChild($text); } return $dom; } /** * @param string $locFormatStr * @return SiteMap */ public function setUrlTmp($locFormatStr) { $this->locFormatStr = $locFormatStr; return $this; } /** * @param string $replace_str * @return SiteMap */ public function setReplaceStr($replace_str) { $this->replace_str = $replace_str; return $this; } /** * @param bool $formatOutput * @return SiteMap */ public function setFormatOutput($formatOutput) { $this->formatOutput = $formatOutput; return $this; } /** * @param string $priority * @return SiteMap */ public function setPriority($priority) { $this->priority = $priority; return $this; } /** * @param string $changefreq * @return SiteMap */ public function setChangefreq($changefreq) { $this->changefreq = $changefreq; return $this; } /** * @param string $locFormatStr * @return SiteMap */ public function setLocFormatStr($locFormatStr) { $this->locFormatStr = $locFormatStr; return $this; } /** * @param string $saveFilePath * @return SiteMap */ public function setSaveFilePath($saveFilePath) { $this->saveFilePath = $saveFilePath; return $this; } } # 实例化 $sitemap = new SiteMap(); $sitemapxml = $sitemap ->setSite('bbs.aiweline.com') ->setTable('thread') ->setFormatOutput(true) ->setLocFormatStr('https://bbs.aiweline.com/?thread-{tid}.htm')#数据库字段,一般是id ->setReplaceStr('tid')#数据库字段,一般是id ->setChangefreq('always') ->setPriority('0.8') ->setSaveFilePath('sitemap.xml') ->create();
3、实时执行
使用corntab自行配置定时执行AutoSiteMap.php
Crontab设置教程:https://bbs.aiweline.com/thread-68.htm
附件解压密码:bbs.aiweline.com
温馨提示:欢迎注册本站,另:未经作者允许请勿转载。