If you do not want to add a dummy element attribute to your root element, you can manually declare the namespace by adding the xmlns attribute for the i prefix:
<root xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
To do this and as hinted at an existing answer ( It is not possible to add an attribute with a namespace prefix using PHP Simplexml ), you must prefix the new attribute with xmlns: (since the xmlns: namespace prefix is not declared in your document). And since xmlns: is part of the name of this attribute, you need two occurrences of xmlns:
$uri = 'http://www.w3.org/2001/XMLSchema-instance'; $root = new SimpleXMLElement('<root/>'); $root->addAttribute( 'xmlns:xmlns:i', $uri ); ###### $child = $root->addChild('foo'); $child->addAttribute( 'xmlns:i:bar', 'baz'); ###### echo $root->asXml();
Gives (formatted manually for reading):
<?xml version="1.0"?> <root xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <foo i:bar="baz"/> </root>
So, the xmlns: prefix seems to fool it. Please note that if you reload the element after setting this attribute, you can use the namespace url also when adding child elements, and this is without prefix:
$root = new SimpleXMLElement( $root->asXML() ); $child = $root->addChild('foo'); $child->addAttribute( 'i:bar', 'bazy', $uri ); #### echo $root->asXml();
Gives (manually formatted again):
<?xml version="1.0"?> <root xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <foo i:bar="baz"/> <foo i:bar="bazy"/> </root>
This second example is apparently closer to the intended (or at least expected) use.
Note that the only way to do this correctly is to use the more complete (but unfortunately more complex and more detailed) DOMDocument classes. This is described in How to declare an XML namespace prefix using DOM / PHP? .
Olivier 'Ölbaum' Scherler
source share