Repository: o/sitemap-php
Branch: develop
Commit: 64aa134dfeb0
Files: 12
Total size: 14.4 KB
Directory structure:
gitextract_2abp199a/
├── .gitignore
├── LICENSE
├── README.md
├── composer.json
├── phpunit.xml.dist
├── src/
│ ├── AbstractGenerator.php
│ ├── WebSitemapGenerator.php
│ └── WebSitemapItem.php
└── tests/
├── WebSitemapGeneratorTest.php
└── xmls/
├── generated/
│ ├── .gitkeep
│ └── test-start-xml-called.xml
└── test-start-xml-called.xml
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
/vendor/
composer.lock
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2009-2017 Osman Üngür
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: 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](https://github.com/evert/sitemap-php).**
What is sitemap-php ?
----------
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)_
How to use
----------
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.
$sitemap->setPath('xmls/');
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');
w/ method chaining.
$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.
sitemap-0.xml
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://example.com/</loc>
<priority>1.0</priority>
<changefreq>daily</changefreq>
<lastmod>2011-04-07</lastmod>
</url>
<url>
<loc>http://example.com/about</loc>
<priority>0.8</priority>
<changefreq>monthly</changefreq>
<lastmod>2011-06-25</lastmod>
</url>
<url>
<loc>http://example.com/contact</loc>
<priority>0.6</priority>
<changefreq>yearly</changefreq>
<lastmod>2009-12-14</lastmod>
</url>
<url>
<loc>http://example.com/otherpage</loc>
<priority>0.5</priority>
</url>
</urlset>
sitemap-index.xml
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>http://example.com/sitemap/sitemap-0.xml</loc>
<lastmod>2011-04-07</lastmod>
</sitemap>
</sitemapindex>
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.**
$ rm -rv sitemap-*
For the truncating a file with php, use the following snippet:
$handle = fopen("/path/to/sitemap/file.xml", "w");
fclose($handle);
================================================
FILE: composer.json
================================================
{
"name": "osm/sitemap-php",
"description": "Fast and lightweight library for generating Google sitemap XML files and index of sitemaps",
"type": "library",
"license": "MIT",
"homepage": "https://github.com/o/sitemap-php/",
"authors": [
{
"email": "osmanungur@gmail.com",
"name": "Osman Ungur"
},
{
"homepage": "https://github.com/o/sitemap-php/graphs/contributors",
"name": "Community"
}
],
"keywords": [
"google",
"sitemap",
"generator",
"xml",
"seo"
],
"require": {
"php": ">=5.6"
},
"require-dev": {
"phpunit/phpunit": "^5.7"
},
"autoload": {
"psr-4": {
"Osm\\Sitemap\\": "src/"
}
},
"minimum-stability": "dev"
}
================================================
FILE: phpunit.xml.dist
================================================
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="./vendor/autoload.php">
<testsuites>
<testsuite name="Sitemap PHP Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<groups>
<exclude>
<group>benchmark</group>
</exclude>
</groups>
</phpunit>
================================================
FILE: src/AbstractGenerator.php
================================================
<?php
namespace Osm\Sitemap;
use XMLWriter;
abstract class AbstractGenerator
{
const EXTENSION_XML = '.xml';
const SEPARATOR = '-';
/**
* @var XMLWriter
*/
protected $xmlWriter;
/**
* @var string
*/
protected $baseUrl;
/**
* @var string
*/
protected $fileName;
/**
* @var string
*/
protected $directory;
/**
* @var integer
*/
protected $maximumUrlCount;
/**
* @var integer
*/
protected $currentUrlCount = 0;
/**
* @var integer
*/
protected $currentFileCount = 0;
/**
* AbstractGenerator constructor.
*/
public function __construct()
{
$this->maximumUrlCount = $this->getDefaultMaximumUrlCount();
}
abstract protected function getDefaultMaximumUrlCount();
abstract protected function startXml();
/**
* @return int
*/
public function getMaximumUrlCount()
{
return $this->maximumUrlCount;
}
/**
* @param int $maximumUrlCount
*/
public function setMaximumUrlCount($maximumUrlCount)
{
$this->maximumUrlCount = $maximumUrlCount;
}
public function getCurrentXmlFileName()
{
if ($this->currentFileCount) {
return $this->directory.DIRECTORY_SEPARATOR.$this->fileName.self::SEPARATOR.$this->currentFileCount.self::EXTENSION_XML;
}
return $this->directory.DIRECTORY_SEPARATOR.$this->fileName.self::EXTENSION_XML;
}
protected function openXml()
{
$this->xmlWriter = new XMLWriter();
$this->xmlWriter->openURI($this->getCurrentXmlFileName());
$this->xmlWriter->startDocument('1.0', 'UTF-8');
$this->xmlWriter->setIndent(true);
$this->startXml();
}
public function closeXml()
{
$this->xmlWriter->endElement();
$this->xmlWriter->endDocument();
}
/**
* @return bool
*/
protected function shouldANewFileToBeCreated()
{
return ($this->currentUrlCount % $this->maximumUrlCount) === 0;
}
/**
* @return string
*/
public function getBaseUrl()
{
return $this->baseUrl;
}
/**
* @return string
*/
public function getFileName()
{
return $this->fileName;
}
/**
* @return string
*/
public function getDirectory()
{
return $this->directory;
}
/**
* @return int
*/
public function getCurrentUrlCount()
{
return $this->currentUrlCount;
}
/**
* @return int
*/
public function getCurrentFileCount()
{
return $this->currentFileCount;
}
}
================================================
FILE: src/WebSitemapGenerator.php
================================================
<?php
namespace Osm\Sitemap;
class WebSitemapGenerator extends AbstractGenerator
{
const SCHEMA = 'http://www.sitemaps.org/schemas/sitemap/0.9';
const DEFAULT_DIRECTORY = './';
const DEFAULT_FILENAME = 'sitemap';
public function __construct($baseUrl, $directory = self::DEFAULT_DIRECTORY, $fileName = self::DEFAULT_FILENAME)
{
parent::__construct();
$this->baseUrl = $baseUrl;
$this->directory = $directory;
$this->fileName = $fileName;
}
protected function getDefaultMaximumUrlCount()
{
return 50000;
}
protected function startXml()
{
$this->xmlWriter->startElement('urlset');
$this->xmlWriter->writeAttribute('xmlns', self::SCHEMA);
}
protected function getFormattedLastModifiedDate(\DateTime $dateTime)
{
return $dateTime->format(\DateTime::W3C);
}
public function addItem(WebSitemapItem $item)
{
if ($this->shouldANewFileToBeCreated()) {
if ($this->currentFileCount) {
$this->closeXml();
}
$this->openXml();
++$this->currentFileCount;
}
++$this->currentUrlCount;
$this->xmlWriter->startElement('url');
$this->xmlWriter->writeElement('loc', $this->baseUrl.$item->getLocation());
if ($item->getPriority()) {
$this->xmlWriter->writeElement('priority', $item->getPriority());
}
if ($item->getChangeFrequency()) {
$this->xmlWriter->writeElement('changefreq', $item->getChangeFrequency());
}
if ($item->getLastModified()) {
$this->xmlWriter->writeElement(
'lastmod',
$this->getFormattedLastModifiedDate($item->getLastModified())
);
}
$this->xmlWriter->endElement();
return $this;
}
}
================================================
FILE: src/WebSitemapItem.php
================================================
<?php
namespace Osm\Sitemap;
class WebSitemapItem
{
const DEFAULT_PRIORITY = 0.5;
const CHANGE_FREQ_ALWAYS = 'always';
const CHANGE_FREQ_HOURLY = 'hourly';
const CHANGE_FREQ_DAILY = 'daily';
const CHANGE_FREQ_WEEKLY = 'weekly';
const CHANGE_FREQ_MONTHLY = 'monthly';
const CHANGE_FREQ_YEARLY = 'yearly';
const CHANGE_FREQ_NEVER = 'never';
/**
* @var string
*/
private $location;
/**
* @var float
*/
private $priority;
/**
* @var string
*/
private $changeFrequency;
/**
* @var \DateTime
*/
private $lastModified;
/**
* WebSitemapItem constructor.
* @param string $location
*/
public function __construct($location)
{
$this->location = $location;
}
/**
* @return string
*/
public function getLocation()
{
return $this->location;
}
/**
* @param string $location
*/
public function setLocation($location)
{
$this->location = $location;
}
/**
* @return float
*/
public function getPriority()
{
return $this->priority;
}
/**
* @param float $priority
*/
public function setPriority($priority)
{
$this->priority = $priority;
}
/**
* @return string
*/
public function getChangeFrequency()
{
return $this->changeFrequency;
}
/**
* @param string $changeFrequency
*/
public function setChangeFrequency($changeFrequency)
{
$this->changeFrequency = $changeFrequency;
}
/**
* @return \DateTime
*/
public function getLastModified()
{
return $this->lastModified;
}
/**
* @param \DateTime $lastModified
*/
public function setLastModified($lastModified)
{
$this->lastModified = $lastModified;
}
}
================================================
FILE: tests/WebSitemapGeneratorTest.php
================================================
<?php
namespace Osm\Sitemap;
use PHPUnit\Framework\TestCase;
class WebSitemapGeneratorTest extends TestCase
{
const XML_FOLDER = __DIR__. '/xmls/';
const GENERATED_XML_FOLDER = self::XML_FOLDER . 'generated/';
public function testGetDefaultMaximumUrlCount()
{
$g = new WebSitemapGenerator('sitemap.nl');
$this->assertEquals(50000, $g->getMaximumUrlCount());
$g->setMaximumUrlCount(100);
$this->assertEquals(100, $g->getMaximumUrlCount());
}
public function testConstructor()
{
$g = new WebSitemapGenerator('sitemap.nl');
$this->assertEquals('sitemap.nl', $g->getBaseUrl());
$this->assertEquals('./', $g->getDirectory());
$this->assertEquals('sitemap', $g->getFileName());
$h = new WebSitemapGenerator('sub.sitemap.de', '/tmp', 'map');
$this->assertEquals('sub.sitemap.de', $h->getBaseUrl());
$this->assertEquals('/tmp', $h->getDirectory());
$this->assertEquals('map', $h->getFileName());
}
public function testStartXmlCalledAndFileCreated()
{
$filename = 'test-start-xml-called';
$filenameWithExt = $filename.'.xml';
$g = new WebSitemapGenerator('sitemap.nl', self::GENERATED_XML_FOLDER, $filename);
$g->addItem(new WebSitemapItem('/foo'));
$g->closeXml();
$this->assertFileExists(self::GENERATED_XML_FOLDER.$filenameWithExt);
$this->assertXmlFileEqualsXmlFile(
self::XML_FOLDER.$filenameWithExt,
self::GENERATED_XML_FOLDER.$filenameWithExt
);
}
}
================================================
FILE: tests/xmls/generated/.gitkeep
================================================
================================================
FILE: tests/xmls/generated/test-start-xml-called.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>sitemap.nl/foo</loc>
</url>
</urlset>
================================================
FILE: tests/xmls/test-start-xml-called.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>sitemap.nl/foo</loc>
</url>
</urlset>
gitextract_2abp199a/
├── .gitignore
├── LICENSE
├── README.md
├── composer.json
├── phpunit.xml.dist
├── src/
│ ├── AbstractGenerator.php
│ ├── WebSitemapGenerator.php
│ └── WebSitemapItem.php
└── tests/
├── WebSitemapGeneratorTest.php
└── xmls/
├── generated/
│ ├── .gitkeep
│ └── test-start-xml-called.xml
└── test-start-xml-called.xml
SYMBOL INDEX (35 symbols across 4 files)
FILE: src/AbstractGenerator.php
class AbstractGenerator (line 7) | abstract class AbstractGenerator
method __construct (line 52) | public function __construct()
method getDefaultMaximumUrlCount (line 57) | abstract protected function getDefaultMaximumUrlCount();
method startXml (line 59) | abstract protected function startXml();
method getMaximumUrlCount (line 64) | public function getMaximumUrlCount()
method setMaximumUrlCount (line 72) | public function setMaximumUrlCount($maximumUrlCount)
method getCurrentXmlFileName (line 77) | public function getCurrentXmlFileName()
method openXml (line 86) | protected function openXml()
method closeXml (line 97) | public function closeXml()
method shouldANewFileToBeCreated (line 106) | protected function shouldANewFileToBeCreated()
method getBaseUrl (line 114) | public function getBaseUrl()
method getFileName (line 122) | public function getFileName()
method getDirectory (line 130) | public function getDirectory()
method getCurrentUrlCount (line 138) | public function getCurrentUrlCount()
method getCurrentFileCount (line 146) | public function getCurrentFileCount()
FILE: src/WebSitemapGenerator.php
class WebSitemapGenerator (line 5) | class WebSitemapGenerator extends AbstractGenerator
method __construct (line 12) | public function __construct($baseUrl, $directory = self::DEFAULT_DIREC...
method getDefaultMaximumUrlCount (line 20) | protected function getDefaultMaximumUrlCount()
method startXml (line 25) | protected function startXml()
method getFormattedLastModifiedDate (line 31) | protected function getFormattedLastModifiedDate(\DateTime $dateTime)
method addItem (line 36) | public function addItem(WebSitemapItem $item)
FILE: src/WebSitemapItem.php
class WebSitemapItem (line 6) | class WebSitemapItem
method __construct (line 43) | public function __construct($location)
method getLocation (line 51) | public function getLocation()
method setLocation (line 59) | public function setLocation($location)
method getPriority (line 67) | public function getPriority()
method setPriority (line 75) | public function setPriority($priority)
method getChangeFrequency (line 83) | public function getChangeFrequency()
method setChangeFrequency (line 91) | public function setChangeFrequency($changeFrequency)
method getLastModified (line 99) | public function getLastModified()
method setLastModified (line 107) | public function setLastModified($lastModified)
FILE: tests/WebSitemapGeneratorTest.php
class WebSitemapGeneratorTest (line 7) | class WebSitemapGeneratorTest extends TestCase
method testGetDefaultMaximumUrlCount (line 12) | public function testGetDefaultMaximumUrlCount()
method testConstructor (line 21) | public function testConstructor()
method testStartXmlCalledAndFileCreated (line 34) | public function testStartXmlCalledAndFileCreated()
Condensed preview — 12 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (16K chars).
[
{
"path": ".gitignore",
"chars": 24,
"preview": "/vendor/\ncomposer.lock\n\n"
},
{
"path": "LICENSE",
"chars": 1083,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2009-2017 Osman Üngür\n\nPermission is hereby granted, free of charge, to any person "
},
{
"path": "README.md",
"chars": 3767,
"preview": "**For the 90's people, i'm keeping this repository as 5.2 compatible. If you need PSR-0 and Composer compatible version,"
},
{
"path": "composer.json",
"chars": 845,
"preview": "{\n \"name\": \"osm/sitemap-php\",\n \"description\": \"Fast and lightweight library for generating Google sitemap XML file"
},
{
"path": "phpunit.xml.dist",
"chars": 662,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<phpunit backupGlobals=\"false\"\n backupStaticAttributes=\"false\"\n "
},
{
"path": "src/AbstractGenerator.php",
"chars": 2709,
"preview": "<?php\n\nnamespace Osm\\Sitemap;\n\nuse XMLWriter;\n\nabstract class AbstractGenerator\n{\n\n const EXTENSION_XML = '.xml';\n\n "
},
{
"path": "src/WebSitemapGenerator.php",
"chars": 1880,
"preview": "<?php\n\nnamespace Osm\\Sitemap;\n\nclass WebSitemapGenerator extends AbstractGenerator\n{\n\n const SCHEMA = 'http://www.sit"
},
{
"path": "src/WebSitemapItem.php",
"chars": 1915,
"preview": "<?php\n\nnamespace Osm\\Sitemap;\n\n\nclass WebSitemapItem\n{\n\n const DEFAULT_PRIORITY = 0.5;\n\n const CHANGE_FREQ_ALWAYS "
},
{
"path": "tests/WebSitemapGeneratorTest.php",
"chars": 1589,
"preview": "<?php\n\nnamespace Osm\\Sitemap;\n\nuse PHPUnit\\Framework\\TestCase;\n\nclass WebSitemapGeneratorTest extends TestCase\n{\n con"
},
{
"path": "tests/xmls/generated/.gitkeep",
"chars": 0,
"preview": ""
},
{
"path": "tests/xmls/generated/test-start-xml-called.xml",
"chars": 153,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n <url>\n <loc>sitema"
},
{
"path": "tests/xmls/test-start-xml-called.xml",
"chars": 153,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n <url>\n <loc>sitema"
}
]
About this extraction
This page contains the full source code of the o/sitemap-php GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 12 files (14.4 KB), approximately 4.1k tokens, and a symbol index with 35 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.