Search code examples
phpxmlsoapsoap-client

How can I add the nil="true" attribute to a SoapVar when using PHP SoapClient?


Here's how I'm setting up my params for the Soap call:

$params = array(
    "connectionToken"   => $this->token,
    "inboxName"         => $this->inboxName
);
$wrapper = new \stdClass();
$typedVar = new \SoapVar($value, XSD_STRING, "string", "http://www.w3.org/2001/XMLSchema");
$wrapper->anyType = $typedVar;
$params["fnParameterValues"] = $wrapper;

This creates the correct XML structure for the request except that if $value = null then I need to add an attribute to the anyType node of nil="true" (actually more accurately:- xsi:nil="true"). How can I achieve this?


Solution

  • I know it is a bit late, but I had the same problem and the solution I found could be helpful for others.

    If you are using WSDL, the built-in PHP SoapServer should add this attribute automatically to any element with null value that is defined as nillable, to accommodate the element to the WSDL definition.

    If you need to add an attribute manually, the only way to do that seems to be capturing the output and modifying the XML response.

    You can use the Zend SoapServer wrapper (https://docs.zendframework.com/zend-soap/server/) and post-process the response (https://docs.zendframework.com/zend-soap/server/#response-post-processing), like this:

    // Get a response as a return value of handle(),
    // instead of emitting it to standard output:
    $server->setReturnResponse(true);
    
    $response = $server->handle();
    
    if ($response instanceof SoapFault) {
        // Manage exception
        /* ... */
    } else {
        // Post-process response and return it
        // I. e., load response as XML document, add attribute to node...
        /* ... */
    }