php自动生成sitemap地图的代码

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

php自动生成sitemap地图的代码
php自动生成sitemap地图的代码
如何生成sitemap地图呢?本文分享一例php代码,用于自动动态生成最新的.sitemap地图文件,并通知google网站地图的更新,感兴趣的朋友参考下吧。

php自动生成sitemap地图
例子,sitemap.inc.php:主要生成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=”/schemas/sitemap/0.9″xmlns:xsi=”/2001/XMLSchema-instance”
xsi:schemaLocation=”/schemas/si temap/0.9
/schemas/sitemap/0.9/sitemap.xsd ”>’;
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};)/”,”&#38;” ,
strtr($str, $translation));
}
}
>
sitemap.php:调用sitemap.inc.php,具体实现sitemap。

复制代码代码示例:
<?php
// redirect requests to dynamic to their keyword rich versions require_once ‘/sitemap.inc.php’;
define(‘SITE_DOMAIN’, ‘’);
// create the Sitemap object
$s = new Sitemap();
// add sitemap items
$s->addItem(SITE_DOMAIN);
$s->addItem(SITE_DOMAIN.”/aboutus.html”);
$s->addItem(SITE_DOMAIN.”/whatnew.php”);

//连接数据库,生成URL并通过条用$s->addItem()加入到
sitemap中。

// output sitemap
if (isset($_GET['target']))
{
// generate Google sitemap
if (($target = $_GET['target']) == ‘google’)
{
echo $s->getGoogle();
}
}
>
说明:
.htaccess文件,重定向sitemap.xml文件到sitemap.php。

RewriteEngine on
RewriteRule ^sitemap.xml$ sitemap.php?target=google [L] ping_google()函数,在网站内容更新的地方调用此函数,用于自动通知Google网站地图更新。

代码:
复制代码代码示例:
<?php
function ping_google(){
$sitemapUrl = ‘/sitemap.xml’;
$pingUrl = “/webmasters/sitemaps/ping?sitemap =”.urlencode($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服务器网站内容更新。

下载全文。

相关文档
最新文档