Error handling omitted for brevity.
<?php
$sxe = simplexml_load_string('<books><book><title>blah</title></book></books>');
$elt = Dom\import_simplexml($sxe);
$elt->setAttribute("foo", "bar");
echo $sxe->asXML();
?>
The above example will output:
<?xml version="1.0"?>
<books foo="bar"><book><title>blah</title></book></books>