Note that elements opened this way will *remain open* (i.e. the XML will be badly formed and thus invalid) unless *each element* is explicitly closed with XMLWriter::endElement.
If you have multiple elements open, and wish to simply close them all -- including the root element -- this snippet is what you want:
<?php
while ($xml->endElement() !== false) { continue; }
?>
In some cases, XMLWriter::writeElement might serve you better: it writes complete elements, but isn't suitable when you need to loop to generate its contents, unless this is done beforehand.