tags:

views:

239

answers:

4

Hello, 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"&gt;';       
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?

+4  A: 

You need to move the closing '</urlset'> outside of the for loop.

Robert Christie
+2  A: 

This line is wrong:

echo '</urlset>'; } 

You need:

}
echo '</urlset>';  

As you are closing the top level tag multiple times, you are getting that error.

Oded
+2  A: 

You need to move the curly bracket } before the echo. Like so:

$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"&gt;';       
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 =>} 
Marius
A: 

PHP is a templating language. Use it to create your output instead of messing around with concatenating strings. eg.:

<?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/&lt;?php urlencode($row['title']) ?></loc>      
            <changefreq>monthly</changefreq>   
            <priority>0.8</priority>   
        </url>   
    <?php } ?>
</urlset>

With consistent indentation like this, mistakes like getting the </urlset> in the wrong place become immediately obvious instead of a pain to debug.

bobince