php语言 百分网手机站

php自动生成sitemap地图的代码

时间:2020-08-12 16:43:29 php语言 我要投稿

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=”http://www.sitemaps.org/schemas/sitemap/0.9″

  xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

  xsi:schemaLocation=”http://www.sitemaps.org/schemas/sitemap/0.9

  http://www.sitemaps.org/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’, ‘http://www.jbxue.com’);

  // 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();

  }

  }

  ?>

【php自动生成sitemap地图的代码】相关文章:

PHP代码如何规范09-16

PHP常用代码大全09-16

PHP代码运行流程09-11

PHP代码优化技巧09-07

提高PHP代码质量的技巧09-24

如何正确发布PHP代码09-21

如何阅读php源代码09-05

PHP生成Excel报表的方法09-08

PHP生成树的方法介绍08-24

PHP开发常用的10段代码09-16