- Saved searches
- Use saved searches to filter your results more quickly
- License
- o/sitemap-php
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Sitemap.xml
- Пример файла sitemap.xml
- Как создать sitemap.xml на PHP и MySQL
- Файл db.php
- Файл sitemap.php
- Файл .htaccess
- Файл robots.txt
- Как добавить файл sitemap.xml в Яндекс и Google
- Формирование файла sitemap.xml
- Вариант на DOMDocument
- Результат:
- Перенаправление с .php на .xml
- Sitemap в robots.txt
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Library for generating Google sitemap XML files
License
o/sitemap-php
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
For the 90’s people, i’m keeping this repository as 5.2 compatible. If you need PSR-0 and Composer compatible version, here is a fork that maintained by Evert Pot.
Fast and lightweight class for generating Google sitemap XML files and index of sitemap files. Written on PHP and uses XMLWriter extension (wrapper for libxml xmlWriter API) for creating XML files. XMLWriter extension is enabled by default in PHP 5 >= 5.1.2. If you having more than 50000 url, it splits items to seperated files. (In benchmarks, 1.000.000 url was generating in 8 seconds)
Include Sitemap.php file to your PHP document and call Sitemap class with your base domain.
include 'Sitemap.php'; $sitemap = new Sitemap('http://example.com');
Now, we need to define path for saving XML files. This can be relative like xmls or absolute /path/to/your/folder and must be a writable folder. In default it uses same folder with your script.
Generated XML file names defaulted to sitemap-*.xml , you can customize prefix of filenames with setFilename method.
$sitemap->setFilename('customsitemap');
We’ll add sitemap url’s with addItem method. In this method, only first parameter (location) is required.
$sitemap->addItem('/', '1.0', 'daily', 'Today'); $sitemap->addItem('/about', '0.8', 'monthly', 'Jun 25'); $sitemap->addItem('/contact', '0.6', 'yearly', '14-12-2009'); $sitemap->addItem('/otherpage');
$sitemap->addItem('/projects', '0.8')->addItem('/somepage')->addItem('/hiddenpage', '0.4', 'yearly', '01-01-2011')->addItem('/rss');
from a sql result, or whatever.
$query = Doctrine_Query::create() ->select('p.created_at, p.slug') ->from('Posts p') ->orderBy('p.id DESC') ->useResultCache(true); $posts = $query->fetchArray(array(), Doctrine_Core::HYDRATE_ARRAY); foreach ($posts as $post) < $sitemap->addItem('/post/' . $post['slug'], '0.6', 'weekly', $post['created_at']); >
If you need to change domain for sitemap instance, you can override it via setDomain method.
$sitemap->setDomain('http://blog.example.com');
Finally we create index for sitemap files. This method also closes tags of latest generated xml file.
$sitemap->createSitemapIndex('http://example.com/sitemap/', 'Today');
When you run your script, it generates and saves XML files to given path.
http://example.com/ 1.0 daily 2011-04-07 http://example.com/about 0.8 monthly 2011-06-25 http://example.com/contact 0.6 yearly 2009-12-14 http://example.com/otherpage 0.5
http://example.com/sitemap/sitemap-0.xml 2011-04-07
You need to submit sitemap-index.xml to Google Sitemaps.
Please note that, generating sitemaps not overrides any previous generated sitemap file. You need to delete old files before the operation.
For the truncating a file with php, use the following snippet:
$handle = fopen("/path/to/sitemap/file.xml", "w"); fclose($handle);
About
Library for generating Google sitemap XML files
Sitemap.xml
(от англ. site — «сайт», map — «карта») — это файл с перечнем всех страниц сайта, подлежащих индексированию поисковыми системами. Он не должен включать адреса страниц со служебной информацией, например, корзину интернет-магазина или адреса страниц пагинации, начиная со второй. Для небольших сайтов (100-200 страниц) он вовсе не нужен, так как робот поисковой системы сам всё найдёт по ссылкам, а редкие исключения можно добавить через Вебмастер.
Пример файла sitemap.xml
Как создать sitemap.xml на PHP и MySQL
Для базы данных table, содержащей такие столбцы:
+----------------+--------------------------------+-----------------------------+----------------------------+ | id | url | update | meta | | smallint(5) | varchar(255) | timestamp | set('noindex', 'feed', '') | | UNSIGNED | | CURRENT_TIMESTAMP | | | AUTO_INCREMENT | | ON UPDATE CURRENT_TIMESTAMP | | +----------------+--------------------------------+-----------------------------+----------------------------+ | 1 | 2017/02/sitemap-php-mysql.html | 2017-02-14 09:07:30 | | +----------------+--------------------------------+-----------------------------+----------------------------+ | 2 | 2017/02/example.html | 2017-01-26 12:00:00 | noindex | +----------------+--------------------------------+-----------------------------+----------------------------+
Файл db.php
localhost‘, ‘my_user‘, ‘my_password‘, ‘my_db‘); // подключение к серверу MySQL: тут указывается пароль к базе данных if ($mysqli->connect_error) < die('Connect Error (' . $mysqli->connect_errno . ‘) ‘ . $mysqli->connect_error); > > else
Файл sitemap.php
&& in_array($_GET['p'], array('0','1'))): sitemapN($_GET['p']); // in_array($_GET['p'], array('0','1')) убирает невостребованные страницы site.ru/sitemap.xml?p=2, site.ru/sitemap.xml?p=3 и т.д. elseif ($_SERVER['QUERY_STRING'] == ''): sitemap(); else: sitemap404(); endif; function sitemap() < // файл индекса Sitemap // подключить файл с паролем от базы данных define('dbOn', ''); require_once 'абсолютный_адрес/db.php'; if (!$mysqli->set_charset("utf8")) < printf("Ошибка при загрузке набора символов utf8: %s\n", $mysqli->error); exit(); > else < if ($result = $mysqli->query("SELECT FLOOR(id/1000) FROM table WHERE meta NOT LIKE '%noindex%' ORDER BY id DESC LIMIT 1;")) < // 1000 — это максимальное количество адресов страниц сайта, хранящихся в одном Sitemap, которое можно изменить на другое число, но не более 50000; условие WHERE meta NOT LIKE '%noindex%' не заносит адрес страницы в Sitemap, если в столбце meta есть значение noindex $row = $result->fetch_row(); $row = intval($row[0]); header("Content-Type: application/xml;"); echo ''; for ($i=0; $i '; > > $mysqli->close(); exit(); > function sitemapN($i) < // файлы Sitemap define('dbOn', ''); require_once 'абсолютный_адрес/db.php'; if (!$mysqli->set_charset("utf8")) < printf("Ошибка при загрузке набора символов utf8: %s\n", $mysqli->error); exit(); > else < if ($result = $mysqli->query("SELECT url, update FROM table WHERE id> vydelit">1000 ." AND id1000 ." AND meta NOT LIKE '%noindex%' LIMIT 1000;")) < header("Content-Type: application/xml;"); echo 'http://site.ru/sitemap.xml?p='.$i.' '; // http://site.ru/ — это домен рассматриваемого сайта, например, http://shpargalkablog.ru/ > echo ''; while ($row = $result->fetch_assoc()) < echo ' '; > > $mysqli->close(); exit(); > function sitemap404() < // 404 ошибка http_response_code(404); include_once 'http://site.ru/404.php'; // подключить файл со своим оформлением 404 ошибки exit(); >'; > echo ' http://site.ru/'. $row['url'] .' '. date('c', strtotime($row['update'])) .' // тегиpriority
иchangefreq
не являются обязательными и есть большие сомнения относительно того, что они как-то учитываются поисковыми системами
Файл .htaccess
RewriteEngine On # если запись отсутствует RewriteRule ^sitemap.xml$ /sitemap.php
Файл robots.txt
User-agent: * Allow: / # запись для примера, разрешает сканировать все страницы Sitemap: http://site.ru/sitemap.xml
Как добавить файл sitemap.xml в Яндекс и Google
Сообщить поисковым системам о созданном файле с картой сайта можно двумя способами.
- Добавить директиву sitemap с его адресом в файл robots.txt (см. выше)
- Добавить его адрес в соответствующее поле в Вебмастере
- Яндекс,
- Google (справка): нажать кнопку «ДОБАВЛЕНИЕ/ПРОВЕРКА ФАЙЛА SITEMAP» — в всплывающем окне ввести «sitemap.xml» — нажать кнопку «Отправить».
Формирование файла sitemap.xml
Предполагается что в таблице стаей есть даты публикации и последнего изменения
( `date_add` и `date_edit` ).
// Подключение к БД. $dbh = new PDO('mysql:dbname=db_name;host=localhost', 'ЛОГИН', 'ПАРОЛЬ'); $out = ''; // Получение статей из БД. $sth = $dbh->prepare("SELECT * FROM `articles`"); $sth->execute(); $articles = $sth->fetchAll(PDO::FETCH_ASSOC); foreach ($articles as $row) < // Дата изменения статьи. $date = max(array($row['date_add'], $row['date_edit'])); $out .= ' https://example.com/articles/' . $row['id'] . '.html ' . date('Y-m-d', $date) . ' ' . ((($date + 604800) > time()) ? '1' : '0.5') . ' '; > $out .= ' '; header('Content-Type: text/xml; charset=utf-8'); echo $out; exit();
Вариант на DOMDocument
// Подключение к БД. $dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль'); $dom = new DOMDocument('1.0', 'utf-8'); $urlset = $dom->createElement('urlset'); $urlset->setAttribute('xmlns','http://www.sitemaps.org/schemas/sitemap/0.9'); // Получение статей из БД. $sth = $dbh->prepare("SELECT * FROM `articles`"); $sth->execute(); $articles = $sth->fetchAll(PDO::FETCH_ASSOC); foreach($articles as $row) < // Дата изменения статьи. $date = max(array($row['date_add'], $row['date_edit'])); $url = $dom->createElement('url'); // Элемент - URL статьи. $loc = $dom->createElement('loc'); $text = $dom->createTextNode( htmlentities('https://example.com/articles/' . $row['id'] . '.html', ENT_QUOTES) ); $loc->appendChild($text); $url->appendChild($loc); // Элемент - дата последнего изменения статьи. $lastmod = $dom->createElement('lastmod'); $text = $dom->createTextNode(date('Y-m-d', $date)); $lastmod->appendChild($text); $url->appendChild($lastmod); // Элемент - приоритетность (от 0 до 1.0, по умолчанию 0.5). // Если дата публикации/изменения статьи была меньше недели назад ставим приоритет 1. $priority = $dom->createElement('priority'); $text = $dom->createTextNode((($date + 604800) > time()) ? '1' : '0.5'); $priority->appendChild($text); $url->appendChild($priority); $urlset->appendChild($url); > $dom->appendChild($urlset); // Сохранение в файл. $dom->save(__DIR__ . '/sitemap.xml'); // Или отправка в браузер. header('Content-Type: text/xml'); echo $dom->saveXML(); exit();
Результат:
https://example.com/articles/16.html 2016-11-19 1 https://example.com/articles/3.html 2016-11-08 0.5
Перенаправление с .php на .xml
Например данный скрипт лежит в корне сайта с именем sitemap.php, вы хотите чтобы он открывался по адресу https://example.com/sitemap.xml . В файле .htaccess нужно добавить запись:
RewriteEngine On RewriteRule ^sitemap.xml$ sitemap.php [L,QSA]
Если скрипт сделан модулем CMS:
RewriteEngine On RewriteCond % ^/sitemap.xml RewriteRule (.*) /index.php?module=sitemap [L,QSA]
Sitemap в robots.txt
Чтобы поисковые системы знали где расположен файл карты сайта нужно добавить директиву Sitemap в robots.txt:
User-agent: * Sitemap: https://example.com/sitemap.xml