Php 是否将google sitemap标头添加到根元素?

Php 是否将google sitemap标头添加到根元素?,php,xml,validation,xml-namespaces,xml-sitemap,Php,Xml,Validation,Xml Namespaces,Xml Sitemap,我正在创建一个简单的脚本来动态生成Google站点地图,但我有一个小问题,当我查看Google的普通站点地图时,我在名为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/site

我正在创建一个简单的脚本来动态生成Google站点地图,但我有一个小问题,当我查看Google的普通站点地图时,我在名为
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”的声明

我认为这是由于缺少标题造成的。

Google站点地图中的
元素位于XML名称空间中,URI为
http://www.sitemaps.org/schemas/sitemap/0.9

因此,当您创建该元素时,您需要在该名称空间中创建它。为此,您需要名称空间URI和方法:

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

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>
然后,这会将文档扩展到(打印精美):


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

希望这有帮助

相关的:

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