Categories: Development

Add dynamic URLs to sitemap with PHP

I searched around a lot for this one but couldn’t come to a simple conclusion, how could i add dynamic urls (domain.com/user=james) to a site map easily and on the fly?! well I came up with my own solution and it doesn’t need frameworks. It goes as follows:

$date = date('c', time());//date and time formatted for sitemap
$url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];//gets the page and variables that this script is on
$lines = file('sitemap.xml');
$last = sizeof($lines) - 1 ;
unset($lines[$last]);
$fp = fopen('sitemap.xml', 'w');
fwrite($fp, implode('', $lines));
fclose($fp);
//^ the above code deletes the last line from the sitemap.xml file 
$myfile = fopen("sitemap.xml", "a") or die("Unable to open file!");
$txt = "
$url

$date
";
fwrite($myfile, "". $txt);
fclose($myfile);

A sitemap.xml generally look similar to




https://domain/contact/
2017-12-07T12:58:48+11:00


https://domain.com/about/
2017-12-07T12:58:48+11:00


https://domain.com/faq/
2017-12-07T12:58:49+11:00

With the PHP script above, it deletes the last line from the file which is the closing it then adds in a new with the location and time the location was last edited. Finally it closes out with the .

Its simple and it works, just use the script on your page that generates dynamic url’s and you will get them added to your sitemap and indexed in Google.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago