$root = $xml->createElementNS('myNS', 'root');
root不应该在命名空间myNS中.在原始示例中,它没有名称空间.
$x = $xml->createElementNS('myNS', 'x', 'test');
设置p:x的qualifiedName而不是x,以建议您使用p作为此命名空间的前缀的序列化算法.但请注意,对于具有命名空间的XML的读取器,无论是否使用p:都没有语义差异.
这将导致xmlns:p声明输出到< p:x>元素(第一个需要它).如果您希望声明位于根元素上(同样,对于带有命名空间的XML读取器没有区别),您必须明确地设置它的属性.例如.:
$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);