Reputation: 11605
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?
Upvotes: 1
Views: 2635
Reputation: 536329
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/<?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.
Upvotes: 0
Reputation: 58911
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">';
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 =>}
Upvotes: 2
Reputation: 498904
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.
Upvotes: 2
Reputation: 20685
You need to move the closing '</urlset'>
outside of the for loop.
Upvotes: 4