SoapHeader 子节点中的 PHP 命名空间

问题描述:

PHP SoapClient 标头.我在获取子节点中的命名空间时遇到问题.这是我正在使用的代码:

PHP SoapClient Headers. I'm having a problem getting the namespaces in child nodes. Here's the code I'm using:

$security = new stdClass;
$security->UsernameToken->Password = 'MyPassword';
$security->UsernameToken->Username = 'MyUsername';
$header[] = new SOAPHeader('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'Security', $security);
$client->__setSoapHeaders($header);

这是它生成的 XML:

Here's the XML it generates:

<ns2:Security>
  <UsernameToken>
    <Password>MyPassword</Password>
    <Username>MyUsername</Username>
  </UsernameToken>
</ns2:Security>

这是我希望它生成的 XML:

Here's the XML I want it to generate:

<ns2:Security>
  <ns2:UsernameToken>
    <ns2:Password>MyPassword</ns2:Password>
    <ns2:Username>MyUsername</ns2:Username>
  </ns2:UsernameToken>
</ns2:Security>

我需要在 UsernameToken、Password 和 Username 节点中获取命名空间引用.任何帮助将不胜感激.

I need to get the namespace reference into the UsernameToken, Password and Username nodes. Any help would be really appreciated.

谢谢.

David 拥有 正确答案.他也说得对,需要太多的努力和思考.这是一个变体,它封装了使用此特定 wsse 安全标头的任何人的丑陋之处.

David has the right answer. And he is also right that it takes way too much effort and thought. Here's a variation that encapsulates the ugliness for anyone working this particular wsse security header.

清理客户端代码

$client = new SoapClient('http://some-domain.com/service.wsdl');
$client->__setSoapHeaders(new WSSESecurityHeader('myUsername', 'myPassword'));

以及实施...

class WSSESecurityHeader extends SoapHeader {

    public function __construct($username, $password)
    {
        $wsseNamespace = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';
        $security = new SoapVar(
            array(new SoapVar(
                array(
                    new SoapVar($username, XSD_STRING, null, null, 'Username', $wsseNamespace),
                    new SoapVar($password, XSD_STRING, null, null, 'Password', $wsseNamespace)
                ), 
                SOAP_ENC_OBJECT, 
                null, 
                null, 
                'UsernameToken', 
                $wsseNamespace
            )), 
            SOAP_ENC_OBJECT
        );
        parent::SoapHeader($wsseNamespace, 'Security', $security, false);
    }

}