If you are managing a website that has large numbers of pages, it’s very difficult to add all URLs in sitemap one by one Especially if page creation frequency is high. Either you are an SEO or Developer, I am sure you had to face this problem. So today I am here with the solution. It’s very easy but a little tricky.
The sitemap is used to submit all internal URLs to Search Engines like Google, Yahoo, Bing, etc for indexing.
So, Without wasting time let’s learn how to create Dynamic XML Sitemap using PHP
Go to the website root folder or anywhere you want to put a sitemap file. For learning, i am using root path public_html & create a file named sitemap.php & add the source code.
Source Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php require 'include/db_connection.php'; //Include Database connection File //If not created Database connection file the use below line $con = mysqli_connect("localhost", "root", "", "testing"); $querry = "SELECT PropertyID FROM property_list"; //Get Data from SQL Server $result = mysqli_query($con, $querry); $base_url ="http://www.vinebrookhomes.com/property-details/";//Set Base path if complete URLs are not stored in database header("Content-Type: application/xml; charset=utf-8"); //Add Header echo '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL; // Print XML Version echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' . PHP_EOL; while($row = mysqli_fetch_array($result)) //Loop for printing all URLs one by one { echo '<url>' . PHP_EOL; // Print url tag echo '<loc>'.$base_url. $row["PropertyID"] .'/</loc>' . PHP_EOL; // Print URL's echo '<changefreq>daily</changefreq>' . PHP_EOL; // Set indexing Frequency echo '</url>' . PHP_EOL; // End URLs } echo '</urlset>' . PHP_EOL; // End Sitemap ?> |
Output
Wait… It’s not completed yet. Probably you forgot to check the URL. It’s with .php extension. But Google support only .xml sitemap
To solve this problem you need to add this code to the .htaccess file. Its rewrite .php extension to .xml for sitemap.php.
1 2 |
RewriteEngine On RewriteRule ^sitemap2\.xml?$ sitemap2.php |
If you have any question, Kindly reply in comment section. Please like & share if you want more similar posts