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

情到浓时终转凉″ 提交于 2019-11-29 10:57:42
$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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!