Sunday, August 30, 2015

How to Access Web Services using SOAP

Previously I mentioned about accessing Web Services in Communicating with Apple Web Services. It communicates directly with the Web Services by posting a XML to it.

My previous post talks about using Filemaker to access the Web Services. Actually you can use a browser to access it. In actual fact, using browser is the more common methods of accessing Web Services. Most browser has Javascript facility. Javascript has a function called XMLHttpRequest that can access web services. This method is usually called AJAX (Asynchronous Javascript And XML). Using this method, you still send the XML to the Web Services.

It is no joke composing the XML. There is an easier way to access Web Services if you have a web site that runs on PHP. PHP has a module that provides SOAP (Simple Object Access Protocol). What you need to do is to call the function and pass it an array of the parameters.

Generally you need to tell the Web Services what to do with the data. But how to know what to send? Well, it is quite simple. Web services usually uses a language called WSDL (Web Services Definition Language.) If you use a web browser and call the address directly like a web page, it actually returns you a XML telling you what functionality it has and what parameters to provide.

Below is a simple PHP program to communicate with a Web Services. It calls a function called "thefunction" and passes a parameter called $param. It echoes a node name called "result" in the returned XML.

$opt= array('encoding'=>'UTF-8');
$client= new SoapClient("http://webservices_address", $opt);
$param=array('action'=>'theaction');
$test=$client->thefunction($param);
echo $test->functionresponse->result;

Nested parameters can be done by adding arrays in an array like below

array('higherlevel'=>array('lowerlevel'=>'xxx','lowerlevel2=>'yyy'))

Note that php actually parses the returned xml automatically into an object array. You need to use the object reference method to access individual values. Converting the object to other form is beyond the scope of this blog.

There are some Web Services that require client cert. This can be easily done by adding "'local_cert=>'certname.pem'" to the variable $opt. The cert and key must be in the same file.