How to make sitemap php

Create a sitemap in PHP with this example: Learn how to generate an XML sitemap using PHP, and how to submit it to search engines.

Creating a Sitemap with PHP

A sitemap is a navigation tool for websites that helps search engine crawlers to better understand the structure of a website and its content. It is also a helpful guide for visitors to get an overview of the website’s content. Creating a sitemap with PHP is a straightforward process, and it can be done in a few easy steps.

The first step is to create a file called “sitemap.php”. In this file, we will define an array containing the URLs of the pages in the website:

$sitemap = array(
  'http://example.com/',
  'http://example.com/about',
  'http://example.com/contact',
  'http://example.com/blog'
);

Next, we will use a foreach loop to loop through the array and output the URLs on the page:

foreach ($sitemap as $url) {
  echo '<a href="' . $url . '">' . $url . '</a><br>';
}

Once the loop is complete, the page should display a list of links to the various pages in the website. Lastly, we need to add a header to the page to let search engine crawlers know that this is a sitemap:

header('Content-Type: text/xml; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

Finally, we need to loop through the URLs again and output them in the correct XML format:

foreach ($sitemap as $url) {
  echo '<url>';
  echo '<loc>' . $url . '</loc>';
  echo '</url>';
}

echo '</urlset>';

That’s it! We now have a fully functional sitemap that can be used by search engine crawlers to better understand the structure of the website.

Answers (0)