【问题标题】:Remove automatically applied namespace in php's SimpleXML删除 php 的 SimpleXML 中自动应用的命名空间
【发布时间】: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


【解决方案1】:

addChild将命名空间作为第三个参数:

$requesterCredentials = $header->addChild('RequesterCredentials', null, 'urn:ebay:api:PayPalAPI');
$credentials = $requesterCredentials->addChild('Credentials', null, 'urn:ebay:apis:eBLBaseComponents');
$credentials->addChild('Username', 'foo', 'urn:ebay:apis:eBLBaseComponents');
$credentials->addChild('Password', 'bar', 'urn:ebay:apis:eBLBaseComponents');

【讨论】:

    猜你喜欢
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    相关资源
    最近更新 更多