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 sitemap 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 </urlset>
$myfile = fopen("sitemap.xml", "a") or die("Unable to open file!");
$txt = "<url>
<loc>$url</loc>
</url>
<lastmod>$date</lastmod>
</urlset>";
fwrite($myfile, "". $txt);
fclose($myfile);

A sitemap.xml generally look similar to

<?xml version="1.0" encoding="UTF-8"?>
<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">
<url>
<loc>https://domain/contact/</loc>
<lastmod>2017-12-07T12:58:48+11:00</lastmod>
</url>
<url>
<loc>https://domain.com/about/</loc>
<lastmod>2017-12-07T12:58:48+11:00</lastmod>
</url>
<url>
<loc>https://domain.com/faq/</loc>
<lastmod>2017-12-07T12:58:49+11:00</lastmod>
</url>
</urlset>

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

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.