Unfortunately, SimpleXML by itself does not easily allow you to do what you want to do. Luckily, DOM does (FIXED):
// Create a new DOMDocument
$dom = new DOMDocument('1.0', 'utf-8');
// Create the DocumentElement
$documentElement = $dom->appendChild($dom->createElement('objects'));
// Loop the SimpleXML elements and import them into DOM
foreach ($val as $element) {
$documentElement->appendChild($dom->importNode(dom_import_simplexml($element), TRUE));
}
// Save to file
$dom->save("c:\\aaa.xml");