简体   繁体   中英

Creating A PHP Sitemap XML Script

I have a database driven website that I add to every day & I want to make an xml sitemap for google with php but I'm really unsure of how to do this. Using the code that I'm used to I created this:

<?php
$get_articles_sql = "SELECT * FROM articles ORDER BY added DESC";
$get_articles_res = mysqli_query($con, $get_articles_sql);
while($article = mysqli_fetch_assoc($get_articles_res)){
    $article_id = $article["id"];
    $article_title = $article["title"];
    $article_added = $article["added"];
    $article_date = date('Y-M-D', strtotime($article_added));

    $article_url_title = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $article_title);
    $article_url_title = strtolower(str_replace(" ","-",$article_url_title));

    $list_articles .= "

        <url>
            <loc>http://www.website.com/article.php?id=$article_id&title=$article_url_title</loc>
            <lastmod>$article_date</lastmod>
            <changefreq>monthly</changefreq>
            <priority>0.8</priority>
        </url>

    ";
?>
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <url>
      <loc>http://www.website.com</loc>
      <lastmod>2005-01-01</lastmod>
      <changefreq>daily</changefreq>
      <priority>1.0</priority>
   </url>
   <?php echo $list_articles; ?>
</urlset>

However, this returns an error on the <?xml line. Is there a correct way of doing it using the code method that I'm using?

Your server probably has short tags enabled which causes the <? in the XML declaration to throw a parse error. The easiest work around is to just echo that line out.

echo '<?xml version="1.0" encoding="UTF-8"?>'
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

It also looks like you're missing the closing bracket to your while loop but I am assuming that is merely a typo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM