XML 错误:仅允许一个顶级元素
我收到 XML 错误:“XML 文档中只允许有一个顶级元素。”当我尝试在 PHP 中运行站点地图脚本时:
$num_rows = mysql_num_rows(mysql_query("SELECT * FROM pages_content WHERE date < CURRENT_TIMESTAMP"));
$result = mysql_query("SELECT * FROM pages_content WHERE date < CURRENT_TIMESTAMP ORDER BY id DESC") or die("Query failed");
echo '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.google.com/schemas/sitemap/0.84">';
for($i=0;$i<$num_rows; $i++) {
$url_product = 'http://www.hostcule.com/'.mysql_result($result,$i,"title");
echo'
<url>
<loc>'.$url_product.'</loc>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
';
echo '</urlset>'; }
有什么问题吗?
I recieve XML error: "Only one top level element is allowed in an XML document." when I try to run my sitemap script in PHP:
$num_rows = mysql_num_rows(mysql_query("SELECT * FROM pages_content WHERE date < CURRENT_TIMESTAMP"));
$result = mysql_query("SELECT * FROM pages_content WHERE date < CURRENT_TIMESTAMP ORDER BY id DESC") or die("Query failed");
echo '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.google.com/schemas/sitemap/0.84">';
for($i=0;$i<$num_rows; $i++) {
$url_product = 'http://www.hostcule.com/'.mysql_result($result,$i,"title");
echo'
<url>
<loc>'.$url_product.'</loc>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
';
echo '</urlset>'; }
What's wrong with it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要将结束
'
移到 for 循环之外。You need to move the closing
'</urlset'>
outside of the for loop.此行是错误的:
您需要:
当您多次关闭顶级标签时,您会收到该错误。
This line is wrong:
You need:
As you are closing the top level tag multiple times, you are getting that error.
您需要将大括号
}
移到 echo 之前。就像这样:You need to move the curly bracket
}
before the echo. Like so:PHP 是一种模板语言。使用它来创建输出,而不是乱七八糟地连接字符串。例如:
通过像这样一致的缩进,诸如将
放在错误位置之类的错误会立即变得明显,而不是调试起来很痛苦。
PHP is a templating language. Use it to create your output instead of messing around with concatenating strings. eg.:
With consistent indentation like this, mistakes like getting the
</urlset>
in the wrong place become immediately obvious instead of a pain to debug.