PHP XML 站点地图生成

5.1.3 2018-06-24 16:00 UTC

README

codecov License Latest Stable Version Total Downloads

一个生成 XML 站点地图的工具。通过 SitemapBundle 与 Symfony 集成。

安装

composer require "thepixeldeveloper/sitemap"

基本用法

生成典型的 (<urlset>) 站点地图。

<?php declare(strict_types=1);

use Thepixeldeveloper\Sitemap\Urlset;
use Thepixeldeveloper\Sitemap\Url;
use Thepixeldeveloper\Sitemap\Drivers\XmlWriterDriver;

$url = new Url($loc);
$url->setLastMod($lastMod);
$url->setChangeFreq($changeFreq);
$url->setPriority($priority);

$urlset = new Urlset();
$urlset->add($url);

$driver = new XmlWriterDriver();
$urlset->accept($driver);

echo $driver->output();

生成父 (<sitemapindex>) 站点地图。

<?php declare(strict_types=1);

use Thepixeldeveloper\Sitemap\SitemapIndex;
use Thepixeldeveloper\Sitemap\Sitemap;
use Thepixeldeveloper\Sitemap\Drivers\XmlWriterDriver;

// Sitemap entry.
$url = new Sitemap($loc);
$url->setLastMod($lastMod);

// Add it to a collection.
$urlset = new SitemapIndex();
$urlset->add($url);

$driver = new XmlWriterDriver();
$urlset->accept($driver);

echo $driver->output();

扩展

支持以下扩展: ImageLinkMobileNewsVideo。它们的工作方式如下(以图像为例)

<?php declare(strict_types=1);

use Thepixeldeveloper\Sitemap\Urlset;
use Thepixeldeveloper\Sitemap\Url;
use Thepixeldeveloper\Sitemap\Extensions\Image;

$url = new Url($loc);
$url->setLastMod($lastMod);
$url->setChangeFreq($changeFreq);
$url->setPriority($priority);

$image = new Image('https://image-location.com');

$url->addExtension($image);

...

高级用法

处理指令

您可以在输出上添加如下处理指令。

<?php declare(strict_types=1);

use Thepixeldeveloper\Sitemap\Drivers\XmlWriterDriver;

$driver = new XmlWriterDriver();
$driver->addProcessingInstructions('xml-stylesheet', 'type="text/xsl" href="/path/to/xslt/main-sitemap.xsl"');

这将添加在文档开始之前。

<?xml-stylesheet type="text/xsl" href="/path/to/xslt/main-sitemap.xsl"?>

注释

注释对于包含文件创建时间等信息很有用。

<?php declare(strict_types=1);

use Thepixeldeveloper\Sitemap\Drivers\XmlWriterDriver;

$date = date('Y-m-d H:i:s');

$driver = new XmlWriterDriver();
$driver->addComment('This XML file was written on ' . $date . '. Bye!');

这将输出。

<?xml version="1.0" encoding="UTF-8"?>
<!--This XML file was written on 2018-06-24 15:57:23. Bye!-->