php – 带命名空间的DOMDocument
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 带命名空间的DOMDocument,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2261字,纯文字阅读大概需要4分钟。
内容图文
![php – 带命名空间的DOMDocument](/upload/InfoBanner/zyjiaocheng/789/bd03793af9a94c7b8af8f045255633cc.jpg)
我已经工作了几个小时试图让输出XML与我给出的规范相匹配,而我却找不到合适的代码来完成它.我正在使用DOMDocument,因为我读到它比SimpleXML更灵活.
期望的最终结果:
<?xml version="1.0" encoding="UTF-8"?>
<retail xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<partnerid>XYZ</partnerid>
<customer xmlns:a="http://schemas.datacontract.org/2004/07/DealerTrack.DataContracts.CreditApp">
<a:info>
<a:FirstName>Bob</a:FirstName>
<a:LastName>Hoskins</a:LastName>
</a:info>
</customer>
<refnum i:nil="true"/>
</retail>
…以及我用来实现的代码(缩写):
$node = new DOMDocument('1.0', 'UTF-8');
$root = $node->createElementNS( 'http://www.w3.org/2001/XMLSchema-instance', 'retail' );
$root->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xmlns:i', 'test');
$capp = $node->appendChild($root);
$cnode = $node->createElement("partnerid", 'XYZ');
$capp->appendChild($cnode);
……这不是我想要的东西.我已经尝试了至少十几个createElementNS,setAttributeNS的组合,查看了几个例子,找不到任何让我接近我所追求的东西.我已经可以在SimpleXML中执行此操作,但我想了解正在发生的事情以及如何在此实例中使用DOM.
解决方法:
除了alex blex回答:对于根元素(并且仅用于它),您还可以简单地创建属性命名空间而不将其附加到根元素.
$dom = new DOMDocument('1.0', 'UTF-8');
$namespaceURIs = [
'xmlns' => 'http://www.w3.org/2000/xmlns/',
'i' => 'http://www.w3.org/2001/XMLSchema-instance',
'a' => 'http://schemas.datacontract.org/2004/07/DealerTrack.DataContracts.CreditApp'
];
$root = $dom->createElement('retail');
$dom->appendChild($root);
$dom->createAttributeNS($namespaceURIs['i'], 'i:attr');
// note that you don't have to append it: `CreateAttributeNS` defines a namespace for
// the entire document and will be automatically attached to the root element.
$root->appendChild($dom->createElement('partnerid', 'XYZ'));
$customer = $dom->createElement('customer');
$customer->setAttributeNS($namespaceURIs['xmlns'], 'xmlns:a', $namespaceURIs['a']);
// `setAttributeNS` allows to define local namespaces, that's why it needs to be
// attached to a particular element.
$root->appendChild($customer);
$info = $dom->createElementNS($namespaceURIs['a'], 'a:info');
$customer->appendChild($info);
// etc.
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();
另外,随意测试其他php XML内置API:XMLWriter
内容总结
以上是互联网集市为您收集整理的php – 带命名空间的DOMDocument全部内容,希望文章能够帮你解决php – 带命名空间的DOMDocument所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。