SimpleXmlElement的命名空间问题

时间:2018-12-05 15:22:52

标签: php xml simplexml

我对SimpleXMLElement有问题。
我必须在此处创建XML:

<p:father>
  <child></child>
</p:father>

如果我尝试使用SimpleXMLElement执行此操作,则结果是:

<p:father>
  <p:child></p:child>
</p:father>

因此所有子代都具有相同的名称空间。 PHP代码是:

$xml = new SimpleXMLElement('<p:father xmlns:p="http://example.com" />');
$xml->addChild('child');

有人可以帮助我吗?我必须执行此操作才能为电子发票创建xml。

1 个答案:

答案 0 :(得分:0)

这里的问题似乎是您在混合命名空间元素和非命名空间元素:给命名空间添加前缀p:,但不要为非前缀元素设置任何默认命名空间。 SimpleXML似乎在“有帮助”地将您的子元素设置为p:命名空间,而不是根本没有命名空间。

我能找到的最干净的解决方案是为未添加前缀的元素定义一个名称空间URI,然后将其传递给addChild调用:

$xml = new SimpleXMLElement('<p:father xmlns:p="http://example.com/prefixed" xmlns="http://example.com/default" />');
$xml->addChild('child', null, 'http://example.com/default');
echo $xml->asXML();

这将导致:

<?xml version="1.0"?> <p:father xmlns:p="http://example.com/prefixed" xmlns="http://example.com/default"><child/></p:father>
相关问题