在根元素中添加谷歌网站地图头?

问题描述 投票:0回答:1

我正在创建一个简单的脚本来动态生成谷歌网站地图,但我有一个小问题,当我查看谷歌的正常网站地图时,我发现在主根元素内的那些行,其中称为 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'。No matching global declaration available for the validation root or Can not find declaration of element 'urlset'.

这是因为缺少头的原因,我想。

php xml validation xml-namespaces xml-sitemap
1个回答
1
投票

<urlset> 元素在谷歌网站地图的XML命名空间中,其URI为 http://www.sitemaps.org/schemas/sitemap/0.9.

因此,当你创建该元素时,你需要在该命名空间内创建它。为此,你需要命名空间的URI和方法的 DOMDocument::createElementNS()文件:

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不可能在属性值中插入换行符。 编码为数字实体。因此,我使用了一个单一的空格,它就是 相当 当文档被读回时。

希望能帮到你。

相关的。

© www.soinside.com 2019 - 2024. All rights reserved.