PHP Namespaces in SoapHeader Child Nodes

David picture David · Nov 20, 2012 · Viewed 8.8k times · Source

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

Here's the XML it generates:

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

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>

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

Thanks.

Answer

dellsala picture dellsala · Dec 10, 2013

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.

Clean client code

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

And the implementation...

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

}