Stopbyte

How to interact with SOAP Web Services with PHP

Hello Guys,

In this tutorial, We want to show to you how to interact with generic soap web services with only few lines of PHP and JAVASCRIPT code.

The most recent technologies allow us to interact with the web objects without spending too many time in coding, then we can increase our productivity in web environment by learning many tricks that we can exploit during our work.

A little brief

SOAP is the web standard protocol with which interact in order to request a web service. Each web service is described by it WSDL definition.

Every ISPs, Company or simply private blogger can offer a web services. As an example, imagine a web service that you can query with for an ip-address in order to retreive the country related to it. Also, imagine another web service with which you can interact in order to discovery the weather of a town. It is Fantastic! :slight_smile: On the web, there are a paramount garden of micro services with which we can interact for our scope!

Let’s know of to interact with SOAP Web services via PHP and Javascript!

The building blocks

The building blocks of this project are two simple objects: A javascript Array and a PHP script.

We will suppose that we want to provide, on our blog, a IP localization service.
For this kind of action, we need a service that take in input a ip address and put out a country!
There are a huge amount of this service on the web: for our test we will use service provided by webservicex.

webserviceX provide many services, related to different fields like Business and Commerce, Messaging, Standards and Lookup Data, Value Manipulation / Unit Converter, Graphics and Multimedia, Utilities and so forth. Of course, we will use a service provided by Utilities Package (GeoIPLocation).

We will start from the Client Side code.

#The client code (jQuery)
In order to use GeoIPService, we only need a simple web page in which we attach the jQuery framework. We added a simple texbox in which user can put an ip address.

<html><head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js integrity="sha256 hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script></head>
<body><input id="ipn" type="text" value="8.8.8.8"/><button onclick="_checkIP()">Check IP</button>

The script is really really really simple! Like an hello world in js :slight_smile:

  <script>
      function _checkIP()
    	{
    		$.ajax({
                          // we pass the value of the input box to our server side 
    		      url: "http://www.arrowsoft.it/example/soap/srv.php?ip="+$("#ipn").val(),  
    		      success: function(data) {
    				data=JSON.parse(data);
    				alert(data["reason"]["GetGeoIPResult"]["CountryName"]);
    		      }
    		});
    		
    	}
    </script>

#The server side code (PHP)
The server side code will read the Ip address from the Ajax request, and also will use PHP SoapClient to query the web service. You have to think nothing. You will only need to pass correct parameter to web service and have to read the answer.

Each web service has their own service description, in WDSL language. If you want to see what is the parameters that you need to pass to the service in order to retreive the Country of the ip, you can check the service WDSL definition here: http://www.webservicex.net/geoipservice.asmx?WSDL

You will see that for the GetGeoIP function, you must pass one parameter to the web service.

<s:schema elementFormDefault="qualified" targetNamespace="http://www.webservicex.net/">
<s:element name="GetGeoIP">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="IPAddress" type="s:string"/>
</s:sequence>
</s:complexType>
</s:element>

Also, you can see that the output of this function will be a complex element in which you can read information about the ip.

<s:element name="GetGeoIPResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="GetGeoIPResult" type="tns:GeoIP"/>
</s:sequence>
</s:complexType>
</s:element>
<s:complexType name="GeoIP">
<s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="ReturnCode" type="s:int"/>
<s:element minOccurs="0" maxOccurs="1" name="IP" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="ReturnCodeDetails" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="CountryName" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="CountryCode" type="s:string"/>
</s:sequence>
</s:complexType>

So, let’s start with coding! :smiley:
Open a PHP file!

<?php
        header('Access-Control-Allow-Origin: *');

        global $soapParameters;
        $soapParameters = Array(
          'login' => "",
          'password' => "",
          'trace' => true
       ) ;
        //web services to query
        $output = array();
        $client = new SoapClient("http://www.webservicex.net/geoipservice.asmx?WSDL",
                $soapParameters
        );
        $param = array();
        $array = array();
        try {
                //parameter to pass to the service
                $param["IPAddress"]=$_GET["ip"];
                array_push($array,$param);
                // call the service
                $w = $client->__call("GetGeoIP",$array);
               //send back to jquery the call result
                $output["reason"]=$w;
        }
        catch(SoapFault $fail) {
                $output["reason"] = $fail->faultstring;
        }
        $output["REQ"]=$client->__getLastRequest();
        $output["RES"]=$client->__getLastResponse();

        echo json_encode($output);
?>