Search code examples
phpsoap-client

Why does the order of SOAP parameters matter in PHP SOAP, and how to fix it?


A comment on the PHP manual states:

If you are using this method, remember that the array of arguments need to be passed in with the ordering being the same order that the SOAP endpoint expects.

e.g //server expects: Foo(string name, int age)

//won't work
$args = array(32, 'john');
$out = $client->__soapCall('Foo', $args);

//will work
$args = array('john', 32);
$out = $client->__soapCall('Foo', $args);

I'm building a SOAP client that dynamically assigns the argument values, which means that it happens that the arguments aren't always in the correct order. This then breaks the actual SOAP call.

Is there an easy solution to this, short of checking the order of the parameters for each call?


Solution

  • An easy solution exists for named parameters:

    function checkParams($call, $parameters) {  
        $param_template = array(
            'Foo' => array('name', 'age'),
            'Bar' => array('email', 'opt_out'),
        );
    
        //If there's no template, just return the parameters as is
        if (!array_key_exists($call, $param_template)) {
            return $parameters;
        }
        //Get the Template
        $template = $param_template[$call];
        //Use the parameter names as keys
        $template = array_combine($template, range(1, count($template)));
        //Use array_intersect_key to filter the elements
        return array_intersect_key($parameters, $template);
    }
    
    
    $parameters = checkParams('Foo', array(
        'age' => 32,
        'name' => 'john',
        'something' => 'else'
    ));
    //$parameters is now array('name' => 'john', 'age' => 32)
    $out = $client->__soapCall('Foo', $parameters);
    

    Not only does it correctly order the parameters, it also filters the parameters in the array.