toto togel terpercaya situs toto terbaik bo togel resmi wla bandar togel terpercaya 10 situs togel terpercaya daftar situs togel terpercaya Slot Gacor slot gacor bandar togel terpercaya bandar togel terpercaya bet 200 phising Phising situs toto PHISING bandar togel toto togel situs togel PHISING agen togel terpercaya bandar togel terpercaya slot demo gacor slot demo situs togel situs togel terpercaya situs togel situs toto togel tototogel bandar togel terpercaya slot maxwin toto slot bandar togel terpercaya bandar togel terpercaya bandar togel terpercaya link togel 10 bandar togel terpercaya 10 situs togel terpercaya situs toto bandar togel bo togel terpercaya Slot Gacor slot gacor bandar togel terpercaya bandar togel terpercaya bet 200 phising Phising bo togel toto togel terpercaya situs togel situs toto togel toto togel terbaik bandar togel terpercaya bo togel situs togel situs togel terpercaya 10 bandar togel terpercaya bandar togel bandar togel terpercaya situs slot bo togel slot anti rungkad toto togel situs togel situs togel terpercaya bandar togel terpercaya situs toto bo togel bandar togel terpercaya bandar togel terpercaya situs toto togel link slot gampang menang 10 situs toto togel 4D link lot 4D Daftar situs togel bandar togel terpercaya situs togel resmi wla 10 situs togel terpercaya toto togel 4D situs togel terpercaya link toto 4D bo togel bandar togel terpercaya bandar togel terpercaya bandar togel terpercaya bandar togel terpercaya slot gacor slot gacor slot gacor tototogel toto togel 4d slot dana situs togel terpercaya slot dana gacor bo togel situs toto togel PHISING situs toto situs toto PHISING bandar togel Slot Gacor slot gacor bandar togel terpercaya bandar togel terpercaya bet 200 phising Phisingslot gacor bo togel terbesar link situs gacor mudah jp bandar togel togel terpercaya 10 bandar togel bet 100 10 situs togel terpercaya situs toto bo togel toto 4D bandar togel terpercaya bandar togel terpercaya bandar togel terpercaya situs togel terpercaya toto slot agen togel terpercaya slot dana slot dana situs slot gacor togel terpercaya situs gacor hari ini situs bandar togel bandar togel bet 100 10 bandar togel mudah jp Slot Gacor slot gacor bandar togel terpercaya bandar togel terpercaya bet 200 phising Phising situs togel bandar togel terpercaya bo togel terpercaya bandar togel situs togel terpercaya situs toto bandar togel PHISING situs toto bandar togel PHISING 5 bandar togel bandar togel terpercaya situs togel terpercaya situs togel terpercaya 10 situs togel terpercaya bandar togel PHISING toto togel toto togel PHISING bandar togel bandar togel terpercaya 10 bandar togel terbesar bandar togel 4D daftar bandar togel bet 100 daftar bandar togel 10 bandar togel gampang maxwin Slot Gacor slot gacor bandar togel terpercaya bandar togel terpercaya bet 200 phising Phising situs togel terpercaya bandar togel terpercaya situs toto togel terpercaya bandar togel terpercaya slot gacor 4d slot luar negeri slot gacor situs togel terpercaya bandar togel terpercaya situs togel terpercaya bandar togel terpercaya situs togel resmi bandar togel terpercaya bandar togel terpercaya slot gacor slot gacor bandar togel terpercaya bo togel terpercaya situs toto 10 bandar togel terpercaya bandar togel terpercaya situs togel terpercaya situs toto togel situs bandar togel 4d bandar togel terpercaya daftar bandar togel 10 bandar togel terbesar bandar togel terbaik 10 bandar togel gampang maxwin slot gacor slot maxwin bandar togel terpercaya agen togel terpercaya bandar togel terpercaya bandar togel terpercaya slot gacor slot gacor bandar togel terpercaya bo togel terpercaya bo togel toto togel bandar togel terpercaya bo togel situs togel terpercaya bandar togel terpercaya slot gacor slot gacor toto togel PHISING situs toto bandar togel PHISING situs toto slot gacor slot gacor situs togel terpercaya bandar togel terpercaya bandar togel terpercaya bandar togel terpercaya toto4d 10 situs togel terpercaya situs togel terpercaya slot gacor slot gacor situs bandar togel terpercaya togel terpercaya bandar togel bet 100 10 bandar togel resmi wla daftar bandar togel terbaik bandar togel terpercaya Slot Gacor slot gacor bandar togel terpercaya bandar togel terpercaya bet 200 phising Phising bandar togel terpercaya situs togel resmi bandar terpercaya situs togel terpercaya slot thailand slot thailand slot luar negeri slot gacor4d situs togel bandar togel toto 4D situs togel terpercaya Slot Gacor slot gacor bandar togel terpercaya bandar togel terpercaya bet 200 phising Phising 10 bandar togel situs toto daftar situs togel terpercaya 10 bandar togel terbesar daftar bandar togel terpercaya situs togel terlengkap 10 bandar togel terpercaya situs toto terpercaya daftar situs toto togel bandar togel bandar togel terpercaya situs bandar togel situs togel Slot Gacor slot gacor phising phising Phising phising slot thailand slot gacor toto 4d bandar togel terpercaya 5 bandar togel terpercaya 10 situs togel terpercaya bandar togel terpercaya situs togel resmi situs togel terpercaya situs togel terpercaya slot thailand slot gacor situs togel terpercaya bandar togel terpercaya toto togel terpercaya situs togel terpercaya situs toto togel 10 bandar togel terpercaya daftar situs togel 10 bandar togel bet 100 daftar bandar togel situs bandar togel slot gacor4d slot thailand bandar togel terpercaya situs toto4d 10 situs togel terpercaya 5 situs togel terpercaya 10 bandar togel terpercaya bandar togel 10 situs togel terpercaya bandar togel resmi wla daftar bandar togel situs togel tototogel toto togel situs toto togel slot thailand slot gacor slot gacor situs togel terpercaya bandar togel terpercaya bandar togel slot gacor slot gacor toto togel slot thailand bandar togel terpercaya slot gacor toto togel link slot gacor slot thailand toto togel bo togel bandar togel situs togel terpercaya bandar togel terpercaya slot thailand tototogel situs togel terpercaya toto togel slot gacor 4d link slot gacor slot gacor4d toto togel situs toto bo togel link toto4d bandar togel 10 situs togel bandar togel bet 100 daftar bandar togel bandar togel resmi wla bandar togel terpercaya Slot Gacor slot gacor bandar togel terpercaya bandar togel terpercaya bet 200 Phising phising situs togel terpercaya slot depo 5k situs togel terpercaya bandar togel terpercaya slot depo 10k paito sydney paito togel bandar togel terpercaya bandar togel situs togel situs toto togel daftar bandar togel toto togel 10 situs togel terpercaya 5 situs togel terpercaya 10 bandar togel terpercaya bandar togel terpercaya bo togel bo togel terpercaya Phising phising Phising phising Phising phising bandar togel terpercaya bandar togel terpercaya situs togel terpercaya bandar togel terpercaya slot demo paito togel bo togel terpercaya situs togel bandar togel terpercaya situs togel terpercaya toto togel 5 bandar togel terpercaya bandar togel situs togel situs bandar togel toto togel togel terpercaya situs toto togel Phising phising Phising phising Phising phising bo togel situs toto situs togel 10 situs togel terpercaya 5 bandar togel terpercaya 10 bandar togel terpercaya bandar togel terpercaya situs togel terpercaya bandar togel terpercaya bandar togel terpercaya bandar togel terpercaya bandar togel terpercaya bandar togel situs toto togel 4d situs bandar togel toto togel situs togel situs toto togel 2 bandar togel terperaya link togel toto4d link bo togel bo togel terpercaya situs togel terpercaya toto togel Phising phising Phising phising phising Phising phising Phising phising Phising phising situs togel terperaya 10 situs togel terpercaya toto4d bandar togel terpercaya situs toto togel link bo togel situs togel terpercaya bandar togel terpercaya situs togel terpercaya bandar togel terpercaya sits toto situs togel terpercaya situs togel resmi situs toto togel situs toto situs togel terpercaya situs toto togel bandar togel terpercaya
easyDRaw.ru | Cоздаем карту сайта sitemap.xml «на лету»

Cоздаем карту сайта sitemap.xml «на лету»

01 Фев 2012 / Дарья Рыбалтович

В данной статье я постараюсь рассказать, как упростить создание и обновление файла sitemap.xml с помощью небольшого скрипта на PHP. Обязательным условием для работы данного скрипта является наличие на сайте базы данных в формате MySQL. Если же ваш сайт написан без использования баз данных, то, по идее можно модифицировать этот скрипт для прохода по дереву папок, но это будет куда больше работы, так что оставляю это на усмотрение фанатов.

Что такое карта сайта sitemap.xml?

Наверняка, посещая различные интернет ресурсы, вы сталкивались с пунктом меню «Карта сайта» или с вот таким значком -  . Так вот, это все нужно и хорошо, но это – для пользователей. А наша с вами задача сделать тоже самое, но для поисковых роботов. Файл sitemap.xml не виден пользователям и выполняет чисто технические задачи.

Sitemap (карта сайта)  – это специальная структура данных в формате XML (Яндекс также поддерживает текстовый формат), которая содержит на одной странице ссылки на все страницы вашего сайта. С ее помощью можно заставить поисковик максимально быстро проиндексировать все страницы вашего сайта. Кроме того, вы сможете указать, какие страницы на сайте являются более важными, задав им приоритет.

Подробная спецификация файла sitemap.xml описана на официальном сайте sitemaps.org.

Cоздание sitemap.xml вручную

Создать карту сайта можно в любом текстовом редакторе, опираясь на базовые знания стандарта XML.

Ниже приведен пример файла Sitemap, в котором содержится только один URL-адрес и использованы все необязательные теги. Необязательные теги выделены курсивом.

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <url>
      <loc>http://easydraw.ru/</loc>
      <lastmod>2012-02-01</lastmod>
      <changefreq>monthly</changefreq>
      <priority>0.8</priority>
   </url>
</urlset>

Генерация sitemap.xml с помощью специальных сервисов

Для создания файла sitemap.xml можно воспользоваться как готовыми сервисами, например, XML-Sitemaps.com (бесплатен, если на сайте до 500 страниц). На главной странице необходимо заполнить форму "Please enter details for sitemap generation" с полями:

  • "Начальный URL (Starting URL)" - в поле ввода нужно указать ссылку на главную страницу сайта,
  • "Частота изменений страниц (Change frequency)" - из выпадающего списка нужно выбрать частоту обновления страниц сайта,
  • "Последнее изменение (Last modification)" - нужно указать, когда страницы сайта в последний раз подвергались изменению("Никогда (None)", "Использовать дату сервера (Use server's response)", "Использовать указанную дату (Use this date/time)"),
  • "Приоритет стрниц (Priority)" - также можно назвать "весом (важностью)" страниц - нужно выбрать из выпадающего списка "Не указывать (None)"

После указания всех необходимых данных нужно нажать на кнопку "Старт (Start)".

Начнется обработка страниц указанного в "Начальный URL (Starting URL)" сайта. Этот процесс займет некоторое время. По его окончании Вам будет предложено скачать файл Sitemap.xml в различных форматах (xml, zip, tar.gz и т.п.).

Файл Sitemap готов! Теперь осталось загрузить его на сервер и составить инструкции поисковикам, где его найти.

Создание собственного скрипта на PHP

Этот способ предпочтителен, если вы знакомы с PHP и любите все делать сами, чисто и красиво. Преимуществом является простота настройки, и быстрота работы сервиса. Настроил один раз – пользуйся хоть всю жизнь, если сайт не поменяет кардинально свою структуру.

Для начала, проверим нашу базу данных, мы будем делать скрипт под таблицу со статьями (в моем случае, это таблица info). В ней обязательно должны присутствовать поля с адресом (url), дата изменения (modify) и приоритет страницы (priority). Первые два поля скорее всего есть, а последнее создается специально для этого скрипта. Кстати, данные в нем хранятся в десятичном формате от 0.1  до 0.9. Поля с приоритетом 0 мы будем игнорировать при выводе в карту сайта.

Создаем файл sitemap.php где-нибудь на сайте, желательно в защищенной директории (подробнее о методах защиты сайта с помощью .htaccess - http://www.softtime.ru/info/apache.php?id_article=27).

Сначала опишем заголовки файла и корневую директорию:


$zag = "<?xml version='1.0' encoding='UTF-8'?>\n<urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'>\n";
$url = "http://easydraw.ru/";
$str = "";
$str0 = " <url>\n\t\t<loc>.".$url."</loc>\n\t\t<priority>0.8</priority>\n\t</url>\n";
$end = "</urlset>";

//создадим соединение с базой и выберем нужные нам записи из таблицы
require_once('constants.inc.php'); //подключаем файл с константами соединения
mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die("Не могу создать соединение ");
mysql_select_db(DB_NAME) or die(mysql_error());
$result = mysql_query ("SELECT url, priority, modify FROM `info` WHERE `priority`<>'0' ") or die (mysql_error()); //выбираем из таблицы все записи

while ($row = mysql_fetch_assoc($result)) {
	$str1 = "\t<url>\n\t\t<loc>".$url.$row[url].".html</loc>\n";  //адрес страницы, если есть страницы во вложенных папках, которые надо проиндексировать, то перед переменной $url можно добавить переменную с категорией
	$str2 = "\t\t<priority>".$row['priority']."</priority>\n"; //приоритетность
	$str3 = "\t\t<lastmod>".$row['modify']."</lastmod>\n"; //дата изменения страницы
	$str4 = "\t</url>\n";
	$str = $str.$str1.$str2.$str3.$str4; //собираем итоговую строку.
}

$str = $zag.$str0.$str.$end;

Теперь добавим обработчик файла:

$file = "./sitemap.xml"; //адрес, куда запишем файл (я пишу в корень)
if(!$handle = fopen($file, "w")){
	echo "Cannot open file ($file)";
	exit;
}

if (fwrite($handle, $str) === FALSE) {
	echo "Cannot write to file ($file)";
	exit;
}

echo "Success";
fclose($handle);

В итоге наш файл будет выглядеть так:

<?php
$zag = "<?xml version='1.0' encoding='UTF-8'?>\n<urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'>\n";
$url = "http://easydraw.ru/";
$str = "";
$str0 = " <url>\n\t\t<loc>.".$url."</loc>\n\t\t<priority>0.8</priority>\n\t</url>\n";
$end = "</urlset>";

require_once('constants.inc.php');
mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die("Не могу создать соединение ");
mysql_select_db(DB_NAME) or die(mysql_error());
$result = mysql_query ("SELECT url, priority, modify FROM `info` WHERE `priority`<>'0' ") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
	$str1 = "\t<url>\n\t\t<loc>".$url.$row['from'].".html</loc>\n";
	$str2 = "\t\t<priority>".$row['priority']."</priority>\n";
	$str3 = "\t\t<lastmod>".$row['modify']."</lastmod>\n";
	$str4 = "\t</url>\n";
	$str = $str.$str1.$str2.$str3.$str4;
}

$str = $zag.$str0.$str.$end;
$file = "./sitemap.xml";
if(!$handle = fopen($file, "w")){
	echo "Cannot open file ($file)";
	exit;
}

if(fwrite($handle, $str) === FALSE) {
	echo "Cannot write to file ($file)";
	exit;
}

echo "Success";
fclose($handle);
?>

Загружаем файл на сервер и запускаем из браузера. Если все сделано правильно, получаем сообщение "Success" и наслаждаемся результатом.

Куда дать знать о sitemap.xml поисковикам

Обычно файл sitemap.xml загружается в корневую папку сайта. Но, при желании, его можно загружать в любую, доступную через браузер папку сайта. Далее, необходимо прописать путь к файлу sitemap.xml в файле robots.txt.

Если на вашем сайте ещё нет файла robots.txt, то нужно создать его минимальную версию, полностью разрешающую всем поисковикам сканирование всего сайта. Для этого нужно сделать файл всего из двух строчек:

User-agent: *
Allow: /

После того, как в нашем распоряжении оказался готовый работающий файл robots.txt, нам нужно добавить всего одну строку.

Sitemap: http://easydraw.ru/sitemap.xml

В данном случае файл sitemap.xml находится в корне сайта и доступен поисковым роботам.

Автор: Дарья Рыбалтович, 01.02.2012

Метки: СЕО, Сайтостроение