sleep-er sleep-er - 3 years ago 202
PHP Question

adding a namespace when using SimpleXMLElement

This is what I am after

<!-- language: lang-xml -->

This is my current code

<!-- language: lang-php -->
$xmlTest = new SimpleXMLElement('<Test/>', 0, false, 'ws', true);
$xmlTest->addChild("ws:somename2", "somevalue2", '');
$make = $xmlTest->addChild('ws:make', null, 'ws');
$make->addChild('ws:model', 'foo', 'ws');
$make->addChild('ws:model', 'bar', 'ws');
header ("Content-Type:text/xml");

but it outputs

<!-- language: lang-xml -->

As you can see the ws: is missing from Test

Answer Source

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', '');
$xmlTest->addAttribute('xmlns:xmlns:xsi', '');

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download