【发布时间】:2015-05-14 08:02:36
【问题描述】:
我正在尝试使用 SimpleXML 为 paypal 快速结帐创建 SOAP 请求。但是,我遇到了一种我还不理解的行为。
信封及其标题是这样生成的:
$envelope = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="urn:ebay:apis:eBLBaseComponents"
xmlns:ns2="urn:ebay:api:PayPalAPI"
/>
');
$header = $envelope->addChild('SOAP-ENV:Header');
$requesterCredentials = $header->addChild('ns2:RequesterCredentials');
$credentials = $requesterCredentials->addChild('ns1:Credentials');
$credentials->addChild('ns1:Username', 'foo');
$credentials->addChild('ns1:Password', 'bar');
产生以下输出:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="urn:ebay:apis:eBLBaseComponents"
xmlns:ns2="urn:ebay:api:PayPalAPI">
<SOAP-ENV:Header>
<SOAP-ENV:RequesterCredentials>
<SOAP-ENV:Credentials>
<SOAP-ENV:Username>foo</SOAP-ENV:Username>
<SOAP-ENV:Password>bar</SOAP-ENV:Password>
</SOAP-ENV:Credentials>
</SOAP-ENV:RequesterCredentials>
</SOAP-ENV:Header>
</SOAP-ENV:Envelope>
现在每个节点都以SOAP-ENV 为前缀,这不是我想要的。只有根节点和标头应以SOAP-ENV 为前缀,其他标签应在addChild() 中添加已定义的命名空间。
期望的输出应该是:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="urn:ebay:apis:eBLBaseComponents"
xmlns:ns2="urn:ebay:api:PayPalAPI">
<SOAP-ENV:Header>
<ns2:RequesterCredentials>
<ns1:Credentials>
<ns1:Username>foo</ns1:Username>
<ns1:Password>bar</ns1:Password>
</ns1:Credentials>
</ns2:RequesterCredentials>
</SOAP-ENV:Header>
</SOAP-ENV:Envelope>
我在这里做错了什么?
【问题讨论】:
-
为了解释发生了什么,SimpleXML 使用元素的命名空间作为默认命名空间。您在没有定义命名空间的情况下追加一个新元素节点,SimpleXML 使用其默认命名空间。前缀经过优化,因此统一为
SOAP-ENV前缀。
标签: php xml dom soap xml-namespaces