How to generate multiple sitemap XML files by php?

by dejuan.watsica , in category: SEO , 10 months ago

How to generate multiple sitemap XML files by php?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by arlo , 10 months ago

@dejuan.watsica 

To generate multiple sitemap XML files using PHP, you can follow these steps:

  1. Create a script that generates a sitemap XML for a specific portion of your website (e.g. blog posts, product categories, etc.)
  2. Create an index XML file that lists all the individual sitemap XML files you've generated (e.g. sitemap_index.xml)
  3. Update your robots.txt file to point to the index file (e.g. Sitemap: http://yoursite.com/sitemap_index.xml)


Here's an example of how your PHP script might generate a sitemap XML for your blog:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
//query your database for your blog posts
$query = "SELECT * FROM blog_posts";
$result = mysqli_query($conn, $query);

//start creating the XML sitemap
$xml = '<?xml version="1.0" encoding="UTF-8"?>';
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

//loop through each blog post and add it to the sitemap
while ($row = mysqli_fetch_array($result)) {
  $xml .= '<url>';
  $xml .= '<loc>http://yoursite.com/blog/' . $row['slug'] . '</loc>';
  $xml .= '<lastmod>' . $row['modified_date'] . '</lastmod>';
  $xml .= '<changefreq>weekly</changefreq>';
  $xml .= '<priority>0.8</priority>';
  $xml .= '</url>';
}

$xml .= '</urlset>';

//save the sitemap XML to a file
$file_path = 'sitemap_blog.xml';
file_put_contents($file_path, $xml);
?>


You would then repeat this process for each section of your website that you want to include in the sitemap index. Once all the individual sitemap XML files are generated, you can create the index file like so:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

  <sitemap>
    <loc>http://yoursite.com/sitemap_blog.xml</loc>
    <lastmod>2021-01-01</lastmod>
  </sitemap>

  <sitemap>
    <loc>http://yoursite.com/sitemap_products.xml</loc>
    <lastmod>2021-01-01</lastmod>
  </sitemap>

</sitemapindex>


This index file should then be accessible at http://yoursite.com/sitemap_index.xml (assuming that's the filename you chose). Finally, update your robots.txt file to include the new sitemap URL:

1
Sitemap: http://yoursite.com/sitemap_index.xml