Accepting Arguments in a SOAP Method






Accepting Arguments in a SOAP Method

Problem

You want your SOAP method to accept parameters.

Solution

Update the method prototype to include arguments:

<?php
class pc_SOAP_return_time {
    public function return_time($tz = '') {
        // set the time zone based on the input
        if ($tz) { $my_tz = date_default_timezone_set($tz); }
        // get the new timestamp
        $date = date('Ymd\THis');
        // reset the time zone to default
        if ($tz) { date_default_timezone_set(ini_get('date.timezone')); }
        // return the timestamp
        return $date;
    }
}

$server = new SOAPServer(null,array('uri'=>'urn:pc_SOAP_return_time'));
$server->setClass('pc_SOAP_return_time');
$server->handle();
?>

Discussion

The basics of serving SOAP requests are covered in Recipe 15.2. This recipe extends that example to demonstrate how to accept method arguments.

Read in parameters by altering the method prototype to include parameter names. Then modify the client request to include data for the additional arguments. Figure modifies the SOAP procedure to accept an optional time zone argument.

Processing SOAP methods with parameters

<?php
class pc_SOAP_return_time {
    public function return_time($tz = '') {
        // set the time zone based on the input
        if ($tz) { $my_tz = date_default_timezone_set($tz); }
        // get the new timestamp
        $date = date('Ymd\THis');
        // reset the time zone to default
        if ($tz) { date_default_timezone_set(ini_get('date.timezone')); }
        // return the timestamp
        return $date;
    }
}

$server = new SOAPServer(null,array('uri'=>'urn:pc_SOAP_return_time'));
$server->setClass('pc_SOAP_return_time');
$server->handle();
?>

The SOAP client can now pass in a tz option. Here it's Europe/Oslo:

<?php
$opts = array('location' => 'http://api.example.org/getTime',
              'uri' => 'urn:pc_SOAP_return_time');

$client = new SOAPClient(null, $opts);

$result = $client->__soapCall('return_time', array('tz' => 'Europe/Oslo'));

print "The local time is $result.\n";
?>

With the new setting, the server returns a time nine hours ahead of the previous one:

The local time is 20060816T173225.

You can pass strings, numbers, arrays, and objects to a SOAP method. The ext/soap extension converts them from XML to native PHP data types.

See Also

Recipe 15.2 for processing SOAP requests without parameters.



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows