adding a namespace when using SimpleXMLElement

SimpleXML has an unusual quirk where the namespace prefixes are filtered from the root element. I’m not sure why it does this.

However, a workaround I’ve used has been to basically prefix the prefix, so that the parser only removes the first ones, and leaves the second

$xmlTest = new SimpleXMLElement('<xmlns:ws:Test></xmlns:ws:Test>', LIBXML_NOERROR, false, 'ws', true);
$xmlTest->addAttribute('xmlns:xmlns:ws', 'http://url.to.namespace');
$xmlTest->addAttribute('xmlns:xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');

This seems to work for me, though I’m interested to understand why SimpleXML does this exactly.

Leave a Comment