1

Error "Uncaught exception 'DOMException' with message 'Namespace Error'" in

 $dom = new DOMDocument('1.0', 'utf-8');
 $root = $dom->createElement('MyRoot','Hello');
 $root->setAttributeNS('http://www.w3.org/1999/xlink','xmlns:xlink','xlink');
 $dom->appendChild($root);
 die($dom->saveXML());

How to set an xmlns declaration at root tag? to produce

  <MyRoot xmlns:xlink="http://www.w3.org/1999/xlink"/>Hello</MyRoot>
Peter Krauss
  • 13,174
  • 24
  • 167
  • 304

2 Answers2

2

The namespace of the xmlns:xlink is not its value, but a standard namespace. The prefix xmlns is used for the standard namespace http://www.w3.org/2000/xmlns/. You do not need to define that namespace.

All namespace attributes (except for xmlns="...") are part of this namespace.

$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('MyRoot','Hello');
$root->setAttributeNS(
  'http://www.w3.org/2000/xmlns/','xmlns:xlink','http://www.w3.org/1999/xlink'
);
$dom->appendChild($root);

echo($dom->saveXML());

Output:

<?xml version="1.0" encoding="utf-8"?>
<MyRoot xmlns:xlink="http://www.w3.org/1999/xlink">Hello</MyRoot>
ThW
  • 19,120
  • 3
  • 22
  • 44
0

Set the XMLNS namespace, then the attribute name of xmlns:xlink, and then the value of the attribute you want to set ... which is the xlink url.

$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('MyRoot','Hello');
$root->setAttributeNS('http://www.w3.org/2000/xmlns/','xmlns:xlink','http://www.w3.org/1999/xlink');
$dom->appendChild($root);
die($dom->saveXML());

<?xml version="1.0" encoding="utf-8"?>
<MyRoot xmlns:xlink="http://www.w3.org/1999/xlink">Hello</MyRoot>
slapyo
  • 2,979
  • 1
  • 15
  • 24