PHP - 在带有 SoapClient 的信封中使用多个 xmlns

PHP - Use multiple xmlns in Envelope with SoapClient

我正在尝试使用 soap 调用信封中的多个 xmlns 名称空间进行 SOAP 调用,但我不知道如何正确执行...

这是我现在拥有的代码:

$soapClient = new SoapClient(WSDL_URL, array(
            "trace" => true,
            "exceptions" => true
        ));
$soapClient->__setLocation(WSDL_LOCATION);

$request = '
        <ns1:someNodeName xmlns="http://some.webservice.url.com">
            <ns2:someOtherNodeName>
                // [REQUEST DETAILS]
            </ns2:someOtherNodeName>
        </ns1:someNodeName>
    ';

$params = new SoapVar($request, XSD_ANYXML);

try {
    $results = $soapClient->someFunctionName($params);
    return $results;
}
catch (Exception $e) {
    $error_xml =  $soapClient->__getLastRequest();
    echo $error_xml . "\n";
    echo $e->getMessage() . "\n";
}

此代码给我一个 XML 请求,如下所示:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://some.webservice.url.com">
    <SOAP-ENV:Body>
        <ns1:someNodeName xmlns="http://some.webservice.url.com">
            <ns2:someOtherNodeName>
                // [REQUEST DETAILS]
            </ns2:someOtherNodeName>
        </ns1:someNodeName>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

我要更改的是信封线,以获得类似的内容:

<SOAP-ENV:Envelope 
    xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 
    xmlns:ns1="http://some.webservice.url.com" 
    xmlns:ns2="http://some.other.webservice.url.com"
>

有什么办法可以实现吗?

XMLNS 属性是命名空间定义,如果您在该命名空间中添加节点,则会添加这些属性。它们不需要在根元素上,而是在使用它的元素或其祖先元素之一上。

$request = '
    <ns1:someNodeName 
       xmlns:ns1="http://some.webservice.url.com"                 
       xmlns:ns2="http://some.other.webservice.url.com">
        <ns2:someOtherNodeName>
            // [REQUEST DETAILS]
        </ns2:someOtherNodeName>
    </ns1:someNodeName>
';

如果您动态创建 XML,您应该使用 XML 扩展,例如 DOM 或 XMLWriter。他们有特定的方法来创建带有命名空间的元素,并将自动添加定义。

$xmlns = [
  'ns1' => "http://some.webservice.url.com",                 
  'ns2' => "http://some.other.webservice.url.com"
];

$document = new DOMDocument();
$outer = $document->appendChild(
  $document->createElementNS($xmlns['ns1'], 'ns1:someNodeName')
);
$inner = $outer->appendChild(
  $document->createElementNS($xmlns['ns2'], 'ns2:someOtherNodeName')
);
$inner->appendChild(
  $document->createComment('[REQUEST DETAILS]')
);

$document->formatOutput = TRUE;
echo $document->saveXml($outer);

输出:

<ns1:someNodeName xmlns:ns1="http://some.webservice.url.com">
  <ns2:someOtherNodeName xmlns:ns2="http://some.other.webservice.url.com">
    <!--[REQUEST DETAILS]-->
  </ns2:someOtherNodeName>
</ns1:someNodeName>