Tuesday, August 9, 2016

Consuming a SOAP web service with PHP

I started programming with PHP at the beginning of 2015, and when is about web services, everything I've read is about RESTful services.

But guess what, is 2016 I will have to interact with a SOAP web service. Doing a research I've discovered this very informative article from Benjamin Eberlei:

http://www.whitewashing.de/2014/01/31/soap_and_php_in_2014.html

Take your time to read it.

OK, now that we know what are we talking about, short example on how to consume a SOAP service. I will use a free SOAP web services for testing:  http://www.webservicex.net

I will test a simple request to this particular service: http://www.webservicex.net/New/Home/ServiceDetail/19 called Periodic table.

The link to the WSDL file is: http://www.webservicex.net/periodictable.asmx?WSDL

With this link and using the SoapClient class from PHP I will write:



<?php

$url = "http://www.webservicex.net/periodictable.asmx?WSDL";
$client = new SoapClient($url);

$fcs = $client->__getFunctions();
$types = $client->__getTypes();
var_dump($fcs);
//var_dump($types);

I do not really need to call __getFunctions() and __getTypes() but is useful for learning purpose.

The output should look like this:

array(8) {
  [3]=>
  string(71) "GetElementSymbolResponse GetElementSymbol(GetElementSymbol $parameters)
 

Where the types of data GetElementSymbolResponse and GetElementSymbol are data types defined in the WSDL file given as parameter to SoapClient constructor.
Let's look to the GetElementSymbol which needs to be passed to the SOAP server.


<s:element name="GetElementSymbol"> 
    <s:complexType>
        <s:sequence>
            <s:element minOccurs="0" maxOccurs="1" name="ElementName" type="s:string"/>
        </s:sequence>
    </s:complexType>
</s:element>

It expect an item called "ElementName". Make sense, let's say I want to find out the symbol for Iron in the periodic table.
Back to my PHP program:


<?php

$res = $client->GetElementSymbol(array('ElementName' => 'Iron'));
//var_dump($res);
echo "Symbol for Iron: ";
echo $res->GetElementSymbolResult;

Evrika! The server answered to our question, the symbol for Iron is "Fe". If you uncomment //var_dump($res); you can see that the response is an object from (stdClass) with one property.
 
 




2 comments: