How to declare XML namespace prefix using DOM / PHP?

I am trying to create the following XML using DOM / PHP5:

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

This is what I do:

$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 get:

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

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

+5
source share
1 answer
$root = $xml->createElementNS('myNS', 'root');

rootmust not be in the namespace myNS. In the original example, it does not have a namespace.

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

p:x x, , p . , XML-- , p: .

, xmlns:p <p:x> (, ). , (-, XML-- ), setAttributeNS. :.

$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);
+10

All Articles