Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an XML namespace prefix with DOM/PHP?

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?

like image 562
yegor256 Avatar asked Aug 27 '10 13:08

yegor256


People also ask

How do you create a namespace prefix in XML?

When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".

What is the correct way to declaring an XML namespace?

Declaring namespaceswhere <name> is the namespace prefix and <"uri"> is the URI that identifies the namespace. After you declare the prefix, you can use it to qualify elements and attributes in an XML document and associate them with the namespace URI.

Can we use DOM in PHP?

So if you're ever working with the content for a post (a post type or a custom post type, for that matter) and you need to manipulate tags much like you would with JavaScript, then using the DomDocument library is one of the most powerful tools are your disposal.

What is namespace in Dom?

The XML Document Object Model (DOM) is completely namespace-aware. Only namespace-aware XML documents are supported. The World Wide Web Consortium (W3C) specifies that DOM applications that implement Level 1 can be non-namespace-aware, and DOM Level 2 features are namespace-aware.


1 Answers

$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);
like image 95
bobince Avatar answered Sep 28 '22 03:09

bobince