2009-12-28 44 views
1

我收到XML错误:“在XML文档中只允许有一个顶级元素。”当我尝试在PHP中运行我的站点地图脚本时:XML错误:只允许一个顶级元素

$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>'; } 

它有什么问题?

回答

4

您需要将闭环'</urlset'>移到for循环之外。

2

此行是错误的:

echo '</urlset>'; } 

您需要:

} 
echo '</urlset>'; 

当您关闭顶层标签多次,你得到这个错误。

2

您需要在echo之前移动大括号}。像这样:

$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> 
    '; 
}//<=To here 
echo '</urlset>'; // move this one =>} 
0

PHP是一种模板语言。使用它来创建您的输出,而不是乱拼接字符串。例如:

<?php 
    $result= mysql_query('SELECT * FROM pages_content WHERE date<CURRENT_TIMESTAMP ORDER BY id DESC') or die('Query failed'); 
?> 
<urlset> 
    <?php while ($row= mysql_fetch_assoc($result)) { ?> 
     <url> 
      <loc>http://www.hostcule.com/<?php urlencode($row['title']) ?></loc>  
      <changefreq>monthly</changefreq> 
      <priority>0.8</priority> 
     </url> 
    <?php } ?> 
</urlset> 

有了这样的一致压痕,就像在错误的地方得到</urlset>失误成为显而易见的,而不是一个痛苦的调试。

相关问题