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 ( 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 ;
$fp = fopen('sitemap.xml', 'w');
fwrite($fp, implode('', $lines));
//^ 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>
fwrite($myfile, "". $txt);

A sitemap.xml generally look similar to

<?xml version="1.0" encoding="UTF-8"?>

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.