phpnamespacessoapserver

php - SoapServer - Need add a namespace in Soap response


I need add a namespace in Soap response. I am using php and SoapServer. My response start like this:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns1="urn:query:request:v2.0">

And I need it to start like this:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns1="urn:query:request:v2.0" xmlns:ns2="urn:query:type:v2.0">

My code in PHP is like this and I don't know how to continue:

class Service
{
// FUNCTIONS
}

$options= array('uri'=>'urn:query:request:v2.0',
    'cache_wsdl' => WSDL_CACHE_NONE);
$server=new SoapServer("Service.wsdl",$options);

$server->setClass('Service');
$server->addFunction(SOAP_FUNCTIONS_ALL);

$server->handle();

Thanks


Solution

  • Namespaces are added dynamically to the soap response body. As long as there is no element with the needed namespace in the soap body, it will not appear. You have to declare it in the response. Here 's a simple example.

    The Soap Request Handling Class

    In this class normally the functions of the soap service are defined. Here happens the magic. You can init SoapVar objects with the namespace they need.

    class Response
    {
        function getSomething()
        {
            $oResponse = new StdClass();
            $oResponse->bla = 'blubb';
            $oResponse->yadda = 'fubar';
    
            $oEncoded = new SoapVar(
                $oResponse,
                SOAP_ENC_OBJECT,
                null,
                null,
                'response',
                'urn:query:type:v2.0'
            );
    
            return $oEncoded;
        }
    }
    

    With PHP 's own SoapVar class you can add namespaces to a node. The fifth paramter is the name of the node while the sixth parameter is the namespace the node belongs to.

    The Soap Server

    $oServer = new SoapServer(
        '/path/to/your.wsdl',
        [
            'encoding' => 'UTF-8',
            'send_errors' => true,
            'soap_version' => SOAP_1_2,
        ]
    );
    
    $oResponse = new Response();
    
    $oServer->setObject($oResponse);
    $oServer->handle();
    

    If the service function getSomething is called, the response would look like the following xml.

    <?xml version="1.0" encoding="UTF-8"?>
    <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="urn:query:type:v2.0">
        <env:Body>
            <ns1:Response>
                <ns1:bla>blubb</ns1:yadda>
                <ns1:blubb>fubar</ns1:blubb>
            </ns1:Response>
        </env:Body>
    </env:Envelope>
    

    As you can see the namespace we have provided to the SoapVar object appears in the envelope node of the soap response.