Friday, May 13, 2011

Web Service Clients in PHP Part 2: SOAP

In my last post I explained how to post to a RESTful web service using CURL. Today I will be posting an example of a SOAP client.

So your imaginary client has now e-mailed you some instructions on how to connect to their SOAP service, probably something like this:

WSDL URL: https://www.example.com/soap/wsdl/ApiUser.wsdl

Method Name: addUser

Parameters: email_address,first_name,last_name (must be passed as an object)

Using this information we can now create our client code:

// first we assign the WSDL url to a variable
$URL = 'https://www.example.com/soap/wsdl/ApiUser.wsdl';

// next we create our soap client using the php SoapClient object
$client = new SoapClient($URL, array("trace" => 1));
  
// we are going to create a standard object to send our parameters
$objRequest = new stdClass();
$objRequest->first_name = 'Jon';
$objRequest->last_name = 'Doe';
$objRequest->email_address = 'jondoe@example.com';
  
// now we wrap our actual web service call in a try catch structure
// this will allow us to catch any exceptions that might be thrown
try { 
    $response = $client->addUser($objRequest); 
} catch ( SOAPFault $e ) {
    $response = ("Error ".$e->faultcode.": ".$e->faultstring); 
}

// now we display the response
echo $response;

Congratulations, thanks to you Jon Doe is now a proud new member of your clients website.

One final note, always read the full documentation when connecting to a web service, there are often little quirks and differences that you will want to be aware of.