使用DOMDocument创建站点地图会引发解析错误


Sitemap creation with DOMDocument throws parsing error

我正在用XML创建一个站点地图,它可以很好地显示一条记录,但当包括1条以上的记录时,它会抛出一个错误:

XML分析错误:文档元素后出现垃圾

此处显示此代码:

<?xml version="1.0" encoding="UTF-8"?>
<url><loc>http://www.mywebsite.com/page/1</loc><changefreq>daily</changefreq><priority>0.6</priority></url>
<url><loc>http://www.mywebsite.com/page/2</loc><changefreq>daily</changefreq><priority>0.6</priority></url>

我的代码:

$xml = new DOMDocument('1.0', 'UTF-8');
for($i = 0; $i < 2; $i++)
{
    $url = $xml->createElement('url');
    $xml->appendChild($url);
    $website_url = 'http://www.mywebsite.com/page/' . $i;
    $loc = $xml->createElement('loc', $website_url);
    $url->appendChild($loc);
    $change = $xml->createElement('changefreq', 'daily');
    $url->appendChild($change);
    $priority = $xml->createElement('priority', '0.6');
    $url->appendChild($priority);
}
header('Content-type: text/xml');
echo $xml->saveXML();

当XML对我来说似乎有效时,它为什么会抛出这种错误?

至少在您的示例中,您有两个根节点(<url>),因为这在xml中是不允许的,第二个是junk after document element

您缺少<urlset>根节点,请参阅:http://www.sitemaps.org/protocol.php