在php的SimpleXML中删除自动应用的命名空间

时间:2015-03-12 08:39:41

标签: php xml dom soap xml-namespaces

我正在尝试使用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>

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

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');