Consuming (.NET) Web services using PHP and NuSoap

Posted by Andrea on 2007-10-23 21:04
In my scenario a .NET Web service offers particular encrypting capabilities.
I need to consume this Web service sending my clear string, I aspect to receive an encrypted string.
The Web service is obviously working properly.

I found this interesting library, so I adopted it:

require_once('lib/nusoap.php');

Here is the code:

// $wsdl:    
// requires web service's specifications aka wsdl
// $parameters:    
// requires following the array 'notation'
// array('parameters' => (array('text' => 'Hello World!!!')));
// that equals to <parameters><text>Hello World!!!</text></parameters>
// $proxy (->host, ->port, ->username, -> password)
// optional, uses a proxy server

function consume_webservice($wsdl, $method, $parameters, $debug = false, $proxy = null)
{
if ($proxy != null)
$proxy->host = $proxy->port = $proxy->username = $proxy->password = false;

$client = new soapclient($wsdl, true, $proxy->host, $proxy->port, $proxy->username, $proxy->password);

$err = $client->getError();
if ($err)
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';

$result = $client->call($method, $parameters);

// check for a fault
if ($client->fault)
{
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
}
else
{
// check for errors
$err = $client->getError();
if ($err)
echo '<h2>Error</h2><pre>' . $err . '</pre>';
}

if ($debug)
{
echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
}

return $result;
}


Last but not least, the usage sample:

$param = array('parameters' => (array('text' => 'test')));
$prova = consume_webservice('http://localhost/cryptography.asmx?WSDL', 'SpecialEncrypt', $param, true);
echo $prova['SpecialEncryptResult'];

This may work (only) with all soap Web services.
Please note that .NET Web services includes all response content into a "parameters" section.