Create a new XML file from PHP

I have created a very basic game in an attempt to learn php. Basically the user selects a set number of words on a html page, which passes that to a php file that randomly selects them using a basic query from a mysql db. The results are then displayed on the php page in XML format.

What I would like it to do is create a new file altogether (i.e. file.xml) rather than just displaying the results in file.php. I am unsure how to write the results pulled from the db to a separate xml file. Any help would be greatly appreciated. My current php code is as follows:


<?
$connection = mysql_connect("localhost", "xxx", "xxx") or die ("Cannot make the connection"); 
$db = mysql_select_db("word", $connection) or die ("Cannot make the connection"); 
if(in_array($_POST['select'], array(3,5,10,20))) { 
  $sql = "SELECT * FROM Random ORDER BY RAND() LIMIT {$_POST['select']}"; 
  $result=mysql_query($sql) or die("query failed: $sql - ". mysql_error()); 
      echo "<?xml version=\"1.0\"?>
"; 
     echo "<words>
";
 while($line = mysql_fetch_assoc($result)) {
 echo "<item>" . $line["Words"] . "</item>
";
 }
 echo "</words>
";
 }
mysql_close($connection);
?>