php自動生成sitemap地圖的程式碼
- php語言
- 關注:6.62K次
如何生成sitemap地圖呢?本文分享一例php程式碼,用於自動動態生成最新的sitemap地圖文件,並通知google網站地圖的更新,感興趣的`朋友參考下吧。
php自動生成sitemap地圖
例子,:主要生成sitemap的類。
程式碼:
複製程式碼 程式碼示例:
<?php
// sitemap generator class
class Sitemap
{
// constructor receives the list of URLs to include in the sitemap
function Sitemap($items = array())
{
$this->_items = $items;
}
// add a new sitemap item
function addItem($url,
$lastmod = ”,
$changefreq = ”,
$priority = ”,
$additional_fields = array())
{
$this->_items[] = array_merge(array(‘loc’ => $url,
‘lastmod’ => $lastmod,
‘changefreq’ => $changefreq,
‘priority’ => $priority),
$additional_fields);
}
// get Google sitemap
function getGoogle()
{
ob_start();
header(‘Content-type: text/xml’);
echo ‘<?xml version=”1.0″ encoding=”UTF-8″?>’;
echo ‘<urlset xmlns=”″
xmlns:xsi=””
xsi:schemaLocation=”
”>’;
foreach ($this->_items as $i)
{
echo ‘<url>’;
foreach ($i as $index => $_i)
{
if (!$_i) continue;
echo “<$index>” . $this->_escapeXML($_i) . “</$index>”;
}
echo ‘</url>’;
}
echo ‘</urlset>’;
return ob_get_clean();
}
// escape string characters for inclusion in XML structure
function _escapeXML($str)
{
$translation = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
foreach ($translation as $key => $value)
{
$translation[$key] = ‘&#’ . ord($key) . ‘;’;
}
$translation[chr(38)] = ‘&’;
return preg_replace(“/&(?![A-Za-z]{0,4}w{2,3};|#[0-9]{2,3};)/”,”&” ,
strtr($str, $translation));
}
}
?>
:呼叫,具體實現sitemap。
複製程式碼 程式碼示例:
<?php
// redirect requests to dynamic to their keyword rich versions
require_once ‘/’;
define(‘SITE_DOMAIN’, ‘’);
// create the Sitemap object
$s = new Sitemap();
// add sitemap items
$s->addItem(SITE_DOMAIN);
$s->addItem(SITE_DOMAIN.”/”);
$s->addItem(SITE_DOMAIN.”/”);
…
//連線資料庫,生成URL並通過條用$s->addItem()加入到sitemap中。
// output sitemap
if (isset($_GET['target']))
{
// generate Google sitemap
if (($target = $_GET['target']) == ‘google’)
{
echo $s->getGoogle();
}
}
?>
說明:
cess檔案,重定向檔案到。
RewriteEngine on
RewriteRule ^$ [L]
ping_google()函式,在網站內容更新的地方呼叫此函式,用於自動通知Google網站地圖更新。
程式碼:
複製程式碼 程式碼示例:
<?php
function ping_google(){
$sitemapUrl = ‘’;
$pingUrl = “($sitemapUrl);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $pingUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch) or die (curl_error()); //執行curl請求
//echo $result;
curl_close($ch);
}
注意:此函式需要開啟php的curl模組。
將以上程式碼加入到網站中,即可實現動態自動生成sitemap檔案了,而且能夠實時通知Google伺服器網站內容更新。
- 文章版權屬於文章作者所有,轉載請註明 https://xuezhezhai.com/zh-tw/jsj/php/gorz52.html