You don’t need to name it sitemap.xml. It can be .php as long as you send a Content-Type header.
Ok, I’m really sick of the Sitepoint message box. Every time I copy-paste code it also copies the colors and puts everything in a sub-box. I’m not going to bother helping people with their code from now on, because I’m going in a huff like a 10 year old. Bye.
One way is to write the xml output directly to a file: http://www.tizag.com/phpT/filewrite.php but if so - don’t run this script from a publicly web accessible directory. Someone could in theory hi-jack the script to write a file with their own contents onto your web server in order to gain access to the machine and use it as a spam server and many other nasty things.
If I were you I’d simply print the xml output to the screen, copy it, paste it, save as xml, and upload it. Takes a bit longer but it’s safer and less code If you only need to run this on a couple sites lazy is good. If you’re going to run this on hundreds of sites then I guess you would want to have the file written via php.