samdark\sitemap\Sitemap::addItem PHP Method

addItem() public method

Adds a new item to sitemap
public addItem ( string $location, integer $lastModified = null, float $changeFrequency = null, string $priority = null )
$location string location item URL
$lastModified integer last modification timestamp
$changeFrequency float change frequency. Use one of self:: constants here
$priority string item's priority (0.0-1.0). Default null is equal to 0.5
    public function addItem($location, $lastModified = null, $changeFrequency = null, $priority = null)
    {
        if ($this->urlsCount === 0) {
            $this->createNewFile();
        } elseif ($this->urlsCount % $this->maxUrls === 0) {
            $this->finishFile();
            $this->createNewFile();
        }
        if ($this->urlsCount % $this->bufferSize === 0) {
            $this->flush();
        }
        $this->writer->startElement('url');
        $this->validateLocation($location);
        $this->writer->writeElement('loc', $location);
        if ($lastModified !== null) {
            $this->writer->writeElement('lastmod', date('c', $lastModified));
        }
        if ($changeFrequency !== null) {
            if (!in_array($changeFrequency, $this->validFrequencies, true)) {
                throw new \InvalidArgumentException('Please specify valid changeFrequency. Valid values are: ' . implode(', ', $this->validFrequencies) . "You have specified: {$changeFrequency}.");
            }
            $this->writer->writeElement('changefreq', $changeFrequency);
        }
        if ($priority !== null) {
            if (!is_numeric($priority) || $priority < 0 || $priority > 1) {
                throw new \InvalidArgumentException("Please specify valid priority. Valid values range from 0.0 to 1.0. You have specified: {$priority}.");
            }
            $this->writer->writeElement('priority', number_format($priority, 1, '.', ','));
        }
        $this->writer->endElement();
        $this->urlsCount++;
    }

Usage Example

Example #1
0
 public function testFrequencyValidation()
 {
     $this->setExpectedException('InvalidArgumentException');
     $fileName = __DIR__ . '/sitemap.xml';
     $sitemap = new Sitemap($fileName);
     $sitemap->addItem('http://example.com/mylink1');
     $sitemap->addItem('http://example.com/mylink2', time(), 'invalid');
     unlink($fileName);
 }
All Usage Examples Of samdark\sitemap\Sitemap::addItem