5

I'm trying to produce the following XML by means of DOM/PHP5:

<?xml version="1.0"?>
<root xmlns:p="myNS">
  <p:x>test</p:x>
</root>

This is what I'm doing:

$xml = new DOMDocument('1.0');
$root = $xml->createElementNS('myNS', 'root');
$xml->appendChild($root);
$x = $xml->createElementNS('myNS', 'x', 'test');
$root->appendChild($x);
echo $xml->saveXML();

This is what I'm getting:

<?xml version="1.0"?>
<root xmlns="myNS">
  <x>test</x>
</root>

What am I doing wrong? How to make this prefix working?

1 Answer 1

11
$root = $xml->createElementNS('myNS', 'root');

root shouldn't be in namespace myNS. In the original example, it is in no namespace.

$x = $xml->createElementNS('myNS', 'x', 'test');

Set a qualifiedName of p:x instead of just x to suggest to the serialisation algorithm that you want to use p as the prefix for this namespace. However note that to an XML-with-Namespaces-aware reader there is no semantic difference whether p: is used or not.

This will cause the xmlns:p declaration to be output on the <p:x> element (the first one that needs it). If you want the declaration to be on the root element instead (again, there is no difference to an XML-with-Namespaces reader), you will have to setAttributeNS it explicitly. eg.:

$root = $xml->createElementNS(null, 'root');
$xml->appendChild($root);
$x = $xml->createElementNS('myNS', 'p:x', 'test');
$root->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:p', 'myNS');
$root->appendChild($x);
Sign up to request clarification or add additional context in comments.

2 Comments

Wow you explained this really well and this one answer has really helped me to understand how namespaces really work in PHP DOM!
@bobince Is this: stackoverflow.com/questions/61530580/… related to this issue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.