【问题标题】:adding google sitemap header to the root element?将谷歌站点地图标题添加到根元素?
【发布时间】:2013-03-05 15:35:55
【问题描述】:

我正在创建一个简单的脚本来动态生成谷歌站点地图,但我有一个小问题,当我查看谷歌的普通站点地图时,我发现那些名为urlset的主根元素内的行:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 

http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" 

xmlns="http://www.sitemaps.org/schemas/sitemap/0.9

我正在通过DOMdocument PHP 创建站点地图,我需要知道如何将此标头或代码添加到我的主要孩子?
这是我的代码:

$doc = new DOMDocument('1.0', 'UTF-8');
$map = $doc->createElement('urlset');
$map = $doc->appendChild($map);
$url = $map->appendChild($doc->createElement('url'));
$url = $map->appendChild($doc->appendChild($url));
$url->appendChild($doc->createElement('loc',$link));
$url->appendChild($doc->createElement('lastmod',$date));
$url->appendChild($doc->createElement('priority',$priority));
$doc->save('sitemap.xml');

代码工作正常,生成 XML 文件没有问题,但是当我尝试通过验证来检查站点地图的有效性时,它给出了这个错误

元素“urlset”:没有可用于验证根的匹配全局声明 要么 找不到元素“urlset”的声明。

这是因为我认为缺少标题。

【问题讨论】:

标签: php xml validation xml-namespaces xml-sitemap


【解决方案1】:

Google Sitemap 中的 <urlset> 元素位于 XML 命名空间中,URI 为 http://www.sitemaps.org/schemas/sitemap/0.9

因此,当您创建该元素时,您需要在该命名空间中创建它。为此,您需要命名空间 URI 和方法 DOMDocument::createElementNS()Docs:

const NS_URI_SITE_MAP = 'http://www.sitemaps.org/schemas/sitemap/0.9';

$doc = new DOMDocument('1.0', 'UTF-8');

$map = $doc->createElementNS(NS_URI_SITE_MAP, 'urlset');
$map = $doc->appendChild($map);

这已经创建了以下 XML 文档:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>

下一部分是为验证添加 XML Schema Instance Schemalocation 属性。它是它自己的命名空间中的一个属性,因此需要在命名空间内再次创建该属性,然后添加到 $map 根元素:

const NS_URI_XML_SCHEMA_INSTANCE = 'http://www.w3.org/2001/XMLSchema-instance';
const NS_PREFIX_XML_SCHEMA_INSTANCE = 'xsi';

$schemalocation = $doc->createAttributeNS(
    NS_URI_XML_SCHEMA_INSTANCE,
    NS_PREFIX_XML_SCHEMA_INSTANCE . ':schemaLocation'
);
$schemaLocation->value = sprintf('%1s %1$s.xsd', NS_URI_SITE_MAP);
$schemaLocation        = $map->appendChild($schemaLocation);

然后将文档扩展为(漂亮的打印):

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
                            http://www.sitemaps.org/schemas/sitemap/0.9.xsd"/>

据我所知,DOMDocument 不可能在 将它们编码为数字实体的属性值内插入换行符。因此,当文档被重新读入时,我使用了一个 等效 的空格。

希望这会有所帮助。

相关:

【讨论】:

    猜你喜欢
    • 2014-12-08
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    相关资源
    最近更新 更多