Web Service, SOAP and PHP 5


A Web service, according to the W3C documentation, is a software system designed to support interoperability between machines on the same network. It has an interface described by a format that can be easily processed by machines: the Web Service Definition Language (WSDL), which is an XML format.

Web service is an abstract concept that must be implemented by a concrete object (called an agent) that must implement a system to send and receive messages. The way it is implemented, and the programming language used, is at the complete discretion of the developer and is indifferent to the client that consumes its services.

There are different types of web services, but the most used are:

REST ( Representational Transfer State ) Web service;
SOAP-type web service.

In this article, we will talk about the SOAP Web service and see how to manage it through the PHP language. If you want to have more information on the differences between the two types of web service, please refer to the lesson Differences between REST and SOAP Web services of the Rest guide.

The SOAP protocol and the Web Service Definition Language (WSDL)

SOAP is a protocol created for the exchange of information between software systems. In the past it was the acronym of Simple Object Access Protocol(which denotes nature to objects of the protocol), but from version 1.2 of the standard the W3C has deleted the acronym.

A SOAP message is defined as a set of information in XML format. An example of a SOAP message, taken from the W3C, is:

<env: Envelope xmlns: env = "http://www.w3.org/2003/05/soap-envelope">
 <Env: Header>
  <n: alertcontrol xmlns: n = "http://example.org/alertcontrol">
   <N: priority> 1 </ n: priority>
   <N: expires> 2001-06-22T14: 00: 00-05: 00 </ n: expires>
  </ W: alertcontrol>
 </ Env: Header>
 <Env: Body>
  <m: alert xmlns: m = "http://example.org/alert">
   <m: msg> Pick up Mary at school at 2pm </ m: msg>
  </ M: alert>
 </ Env: Body>
</ Env: Envelope>

As you can see, the message has a Header-Body structure . Usually the header of a SOAP message contains the information that can be used by the recipient of the message, while the body contains the information to be sent.

Another element present is the SOAP envelope , which is the root element of every SOAP message. It is useful to note that the elements Headerand Bodyare not mandatory. A SOAP message without one of these elements, or without either one, is perfectly legal. The element envelopeis instead mandatory.

As previously written, a Web service has an interface described by a format created to be easily readable by machines. This format is the WSDL.

The WSDL is an XML format used to describe services on the network. It is used to allow clients who want to consume the Web service to know all the features of the Web service itself.

Here we just have to see the most important aspects of the document, who wants a complete explanation of the elements of a WSDL file can read the lesson The elements of a WSDL document of the Web Service Guide.

These are represented by the elements:

  • types: represent the types of data used by the Web service. You can also create complex data types that contain elements of the atomic type (integers, strings, etc.);
  • message: this is the series of messages that the Web service sends and receives thanks to the functions it makes available;
  • portType: represents the most important element of the document. Describes the Web service in terms of the operations it can do and the messages it can exchange with the clients;
  • binding: defines the format of the messages and the protocol for the operations and messages defined in the portType element;
  • service: groups a set of ports (elements port) each connected to a previously defined binding element.

Our first SOAP Web service in PHP

PHP from version 5 has the native classes and functions to interact with a SOAP Web service. The current PHP version supports SOAP versions 1.1 and 1.2 and WSDL version 1.1 .

In particular, the class SoapServerthat allows the creation of an object for a SOAP Web service has been introduced .

The class has the function addFunctionthat allows you to add a function to the object SoapServer, and then to the Web service itself. And the function setClassthat sets the class that will handle SOAP requests. All functions of the assigned class will represent the functions of the Web service.

As an example of Web service we create a service that allows the user to request the internet address of a search engine.

class SearchEngineWS {
function getWebUrl ($ name) {
    $ engines = array (
        'google' => 'www.google.it',
        'yahoo' => 'www.yahoo.it'
    return isset ($ engines [$ name])? $ engines [$ name]: "Search Engine unknown");
$ server = new SoapServer ("search_engine.wsdl");
$ Server-> setClass ( "SearchEngineWS");
$ Server-> handle ();

This simple code instantiates an object of type SoapServer, and sets the class SearchEngineWS. All the functions of the class now represent the functions provided by the Web service . The functions must not be declared privateor protectedotherwise clients can not access them. It is easy to see that these functions could query a database and return dynamic values.

The object’s constructor SoapServercan receive 2 parameters, the second of which is optional. The first one represents the address of the WSDL file that describes the Web service, while the second is an array that allows to define some features of the Web service: the supported SOAP version, the server encoding and the uri actor.

An example of an object SoapServercan be this:

$ server = new SoapServer ("file.wsdl", array ('soap_version' => SOAP_1_2));

You can pass the NULL value as the first parameter. In this case, it is necessary to pass in the second parameter the element actor uri, which represents the destination namespace for the Web service.

When defining a WSDL Web service (hence with the first SoapServernon-null object parameter ), you can use the function getFunctionsto get the list of functions defined in the WSDL file.

Finally, the function handleprocesses a SOAP request and sends a return message to the client requesting it.

A WSDL for our Web service

The WSDL is an XML format created to be easily readable by machines . This means that it is very difficult for a human being to read a WSDL file and interpret it correctly.

For our example, we create this file ( search_engine.wsdl) and put it in the same directory as the Web service:

<?xml version="1.0" encoding ="utf-8"?>
        <xs:schema targetNamespace="http://www.html.it/php_ws_soap">
            <xs:element name="name" type="xs:string" />
            <xs:element name="weburl" type="xs:string" />
    <message name="getWebUrl">
        <part name="name" type="xs:string" />
    <message name="returnWebUrl">
        <part name="weburl" type="xs:string" />
    <portType name="WebServiceTest">
        <operation name="getWebUrl">
            <input message="tns:getWebUrl" />
            <output message="tns:returnWebUrl" />
    <binding name="WebServiceSOAPBinding" type="WebServiceTest">
        <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="getWebUrl">
            <soap:operation soapAction="http://localhost/ws_server/SearchEngineWS.php/getWebUrl" style="rpc"/>
                <soap:body use="encoded" namespace="http://www.html.it/php_ws_soap" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
                <soap:body use="encoded" namespace="http://www.html.it/php_ws_soap" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
    <service name="GetWebUrl">
        <port name="WebUrl" binding="tns:WebServiceSOAPBinding">
            <soap:address location="http://localhost/ws_server/SearchEngineWS.php"/>

Although difficult to understand, we can note the presence of the two types of data string, of the two messages that the Web service will manage (one in input and the other in output) and the operation getWebUrlthat represents the function made available by the Web service. .

The file at http: //localhost/ws_server/SearchEngineWS.php is the file of our Web service where the class has been defined SearchEngineWSwith the method getWebUrl.

A simple SOAP client in PHP

With the SOAP server defined above, we can write a simple client that asks the Web service for the internet address of a search engine. PHP 5 provides the object SoapClientto define a client.

try {
$gsearch = new SoapClient('http://localhost/ws_server/search_engine.wsdl');
} catch (SoapFault $e) {

The object constructor SoapClientcan also receive two parameters, the second of which, an array of options, is optional. The first represents the address of a WSDL file of the Web service.

The object SoapClienthas defined a function __soapCallthat can be used to call a Web service function. It is usually useful in non-WSDL Web services, when the __ function can not be used getFunctions(the same function in the object SoapServeris defined without the two initial low dashes) to obtain the list of functions defined in the Web service.

Error handling shows the object SoapFaultthat is nothing but a class that it inherits from Exception.

If we call this file in a browser we get the answer: www.google.it.



Please enter your comment!
Please enter your name here